【Nodejs】Express implementation interface

introduce

node framework

node-http model ==⇒ express frame ==⇒ koa =⇒ egg.js

Install

npm i express

New method of express packaging

  • express
    • express.static()– Open static resources
    • express.urlencoded()– Get POST request body
  • app
    • app.get()– Handle client’s GET request
    • app.post()– Handle client’s POST request
    • app.use()– Set application level configuration
  • req
    • req.body– Get POST request body
    • req.params– Get GET request dynamic parameters
    • req.query– Get GET request parameters (get query string parameters)
  • res
    • res.sendFile(文件的绝对路径)– Read the file and respond with the result
    • res.set({name, value})– Set response headers
    • res.status(200)– Set response status code
    • res.send(字符串或对象)– response results
    • res.json(对象)– Response results in JSON format
    • res.jsonp()– Response results in JSONP format

Please note that in express we can still use methods from the http module.

Simple requests and complex requests

simple request

If it meets the following conditions, it is asimple request:

  1. The request method can only be: GET, HEAD, POST
  2. And the value of Content-Type is limited to
    • text-plain
    • multipart/form-data
    • application/x-www-form-urlencoded

Complex request

Features:Send two requests

A preflight request will be sent firstOPTIONS

IfOPTIONS allows cross-domain header information, the browser will send a second request

Constructing a web server using Express

nodemonStart the service.
Insert image description here

step

  1. Load express module
  2. Create express server
  3. Start the server
  4. Listen to browser requests and process them
// 1. 导入express模块
const express = require('express')
// 2. 创建服务器
const app = express()
// 3. 启动服务器
app.listen(3000, function () {
    
    
  console.log('服务器启动成功')
})

// express 处理用户请求
// app.get() 用于处理用户的get请求
// app.post() 用于处理用户的post请求
app.get('/index',(req,res) => {
    
    
  res.send('你好,新世界')
})
app.get('/login', (req,res) => {
    
    
  res.send('<h1>哈哈</h1>')
})
// 更多的是返回一个数据(express自动把这个对象转化为JSON )
app.get('/user', (req,res) => {
    
    
  res.send({
    
    
    name: 'zs',
    age: 18,
    gender: '女'
  })
})

Implement get interface

Interface server:

Return data (JSON data) based on the user's request

Implement a simple get interface

const express = require('express')

const app = express()
app.listen(3000, () => {
    
    
  console.log('服务器启动成功了')
})
app.get('/login', (req, res) => {
    
    
  // 允许该接口跨域访问  CROS
  res.setHeader('Access-Control-Allow-Origin', '*') // *表示都可以跨域访问
  res.send({
    
    
    code: 200,
    message: '成功'
    
  })
})

Get query string

What is a query string?

These following the url address:
Insert image description here

Usereq.queryGet query string

  • interface
const express = require('express')

const app = express()
app.listen(3000, () => {
    
    
  console.log('服务器启动成功了')
})
app.get('/login', (req, res) => {
    
    
  // 允许该接口跨域访问
  res.setHeader('Access-Control-Allow-Origin', '*') // *表示都可以跨域访问
  console.log(req.query)
  const {
    
    username, password} = req.query
  if(username === 'admin' && password === '123456') {
    
    
    res.send({
    
    
      code: 200,
      message: '成功'
    })
  } else {
    
    
    res.send({
    
    
      code: 400,
      message: '用户名或密码错误'
    })
  }
})

The query string obtained:

Insert image description here

  • page
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <input type="text" placeholder="请输入用户名" class="username">
  <br>
  <input type="text" placeholder="请输入密  码" class="pwd">
  <br>
  <button>登录</button>
  <script src="node_modules/axios/dist/axios.js"></script>
  <script>
    document.querySelector('button').onclick = async function () {
      
      
      const username = document.querySelector('.username').value
      const password = document.querySelector('.pwd').value
      const res = await axios({
      
      
        method: 'get',
        url: 'http://localhost:3000/login',
        params: {
      
      
          username,
          password
        }
      })
      console.log(res)
    }
  </script>
</body>
</html>

Get dynamic parameters

url/:id/:name/:age: The following are called dynamic parameters

Usereq.paramsto obtain dynamic parameters

app.get('/getUser/:id', (req, res) => {
    
    
  // 允许该接口跨域访问
  res.setHeader('Access-Control-Allow-Origin', '*')
  console.log(req.params)
  res.send({
    
    
    id: req.params.id,
    name: 'zs',
    age: 10

  })
})

Insert image description here
Insert image description here

Interface style

The more popular one at present is REST style, which is a simple interface style.

Performance: id is directly spliced ​​into the url, that is, using dynamic parameters

Implement post request

Note: Since the post request's Content-Type is application/json, it is a complex request.

Send post request steps

  1. Handle all options requests
app.options('*', (req, res) => {
    
    
  // 允许CORS跨域的域名
  res.setHeader('Access-Control-Allow-Origin', '*')
  // 允许CORS跨域的请求方式,默认只有GET,POST
  res.setHeader('Access-Control-Allow-Methods', 'GET,POST,PUT,PATCH,DELETE')
  // 允许CORS跨域请求的请求头
  res.setHeader('Access-Control-Allow-Headers', 'content-type')
  res.send(null)
})
  1. Send post request
app.post('/login', (req, res) => {
    
    
  res.setHeader('Access-Control-Allow-Origin', '*')
  res.send({
    
    
    code: 200,
    message: '登陆成功'
  })
})
  1. If you want to get the request body of the post request
    • usereq.body
    • Must use a built-in middleware**express.json()
app.use(express.json())
...
...
app.post('/login', (req, res) => {
    
    
  res.setHeader('Access-Control-Allow-Origin', '*')
  console.log(req.body)
  res.send({
    
    
    code: 200,
    message: '登陆成功'
  })
})

Insert image description here
Insert image description here

The server receives different types of request bodies and uses them in different ways.

  • urlencoded —> app.use(express.urlencoded({extended: false}));
  • application/json —> app.use(express.json()); – no demo
  • form-data —> The server uses third-party module processing (multer)

middleware

The intermediate processing link in the special business processing process
Insert image description here

  • Middleware is a function, usually written before the request

  • There are three basic parameters

    • req requests related objects
    • res response related objects
    • next function, must call next middleware to pass down
    const express = require('express')
    const app = express()
    // app.use(中间件) // 所有的请求之前都会调用中间件
    const middle = function (req, res, next) {
          
          
      console.log('我是中间件')
      // 处理完一定要记得调用next
      next()
    }
    app.use(middle)
    app.listen(3000, () => {
          
          
      console.log('服务器启动了')
    })
    
    app.get('/login', (req, res) => {
          
          
      res.send('登录')
    })
    app.get('/user', (req, res) => {
          
          
      res.send('用户')
    })
    app.get('/index', (req, res) => {
          
          
      res.send('首页')
    })
    

Insert image description here

Use middleware to solve cross-domain problems

Declare a middlewareAllowCrossDomain

const express = require('express')
const app = express()
// app.use(中间件) // 所有的请求之前都会调用中间件
const AllowCrossDomain = function (req, res, next) {
    
    
  // 允许CORS跨域的域名
  res.setHeader('Access-Control-Allow-Origin', '*')
  // 允许CORS跨域的请求方式,默认只有GET,POST
  res.setHeader('Access-Control-Allow-Methods', 'GET,POST,PUT,PATCH,DELETE')
  // 允许CORS跨域请求的请求头
  res.setHeader('Access-Control-Allow-Headers', 'content-type')
  // 处理完一定要记得调用next
  next()
}
app.use(AllowCrossDomain)
app.listen(3000, () => {
    
    
  console.log('服务器启动了')
})

app.post('/login', (req, res) => {
    
    
  res.send({
    
    
    code: 200,
    message: '登陆成功'
  })
})
app.get('/user', (req, res) => {
    
    
  res.send('用户')
})
app.get('/index', (req, res) => {
    
    
  res.send('首页')
})

express built-in middleware

  1. static

Static resources

// img是一个文件夹
// 直接把img作为公共的静态资源目录
app.use(express.static('img'))
  1. urlencoded
  • deal withapplication/x-www-form-urlencoded
  • Hang the request body on req.body
  1. json
    • deal withapplication/json
    • Hang the request body on req.body

Usually 2 and 3 are used at the same time

// 处理json数据
app.use(express.json())
// 处理form-urlencoded数据
app.use(express.urlencoded({
    
    extended: false}))

Guess you like

Origin blog.csdn.net/qq_41675812/article/details/130524956