首页 > 其他 > 详细

Creating Servers with Express

时间:2021-02-03 10:21:49      阅读:37      评论:0      收藏:0      [点我收藏+]
  • What is express?
    • https://expressjs.com/en/5x/api.html#app.post.method
    • Express is a "fast, unopinionated, minimalist web framework for Node.js:"  It helps us build web apps!
    • It‘s just an NPM package which comes with a bunch of methods and optional plugins that we can use to build web applications and API‘s
  • Express help us:
    • Start up a server to listen for requests
    • Parse incoming requests
    • Match those requests to particular routes
    • Craft our http response and associated content
  • Libraries VS frameworks
    • library: When you use a library, you are in charge! You control the flow of the application code, and you decide when to use the library.
    • framework: With frameworks, that control is inverted.  The framework is in charge, and you are merely a participant! The framework tells you where to plug in the code.
  • Templating
    • Templating allows us to define a preset "pattern" for a webpage, that we can dynamically modify.
    • For example, we could define a single "Search" template that displays all the results for a given search term.  We don‘t know what the term is or how many results there are ahead of time.  The webpage is created on the fly.
  • start with express
    1. mkdir firstapp
    2. cd firstapp

    3. npm init -y(-y省掉设置参数的步骤)
    4. touch index.js

    5. npm install express

    6. npm i -g nodemon (nodemon to auto-restart server)

    7. nodemon index.js
    8. 技术分享图片

技术分享图片

const express = require("express")
const app = express();

app.listen(8080, () => {
    console.log("this is 8080 port")
})

app.get(‘/‘, (req, res) => {
    res.send(‘welcome to the home page~‘)
})

app.get(‘/cat‘, (req, res) => {
    res.send(‘meow~‘)

})

app.post(‘/han‘, (req, res) => {
    res.send(‘Lieeee‘)

}). //open postman, choose post setting, then sent, get Lieeee.

app.get(‘/dog‘, (req, res) => {
    res.send(‘woof~‘)
})

//set multiple parameters app.get(
‘/r/:subreddit/:postID‘, (req, res) => { const { subreddit, postID } = req.params; res.send(`<h1>Viewing Post ID: ${postID} on the ${subreddit} subreddit</h1>`) })
//working with query strings app.get(
‘/search‘, (req, res) => { const { q } = req.query; if (!q) { res.send(‘NOTHING FOUND IF NOTHING SEARCHED!‘) } else { res.send(`<h1>Search results for: ${q}</h1>`) } }) // if can not find matching routing app.get(‘*‘, (req, res) => { res.send("I don‘t know the path~") })

技术分享图片

技术分享图片

技术分享图片

技术分享图片

技术分享图片

Creating Servers with Express

原文:https://www.cnblogs.com/LilyLiya/p/14360103.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!