zoukankan      html  css  js  c++  java
  • Creating Servers with Express

    refer to: https://www.udemy.com/course/the-web-developer-bootcamp/

    • 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

    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~") })

  • 相关阅读:
    2020.12.15
    2020.12.14
    2020.12.13
    2020.12.11
    2020.12.10
    语音合成标记语言(SSML)
    Skyline查询
    win10 VMware 安装 Linux 虚拟机
    图像梯度计算
    Harris Corner Detection
  • 原文地址:https://www.cnblogs.com/LilyLiya/p/14360103.html
Copyright © 2011-2022 走看看