Getting Started with Node.js - Writing Interfaces with Express

1 Introduction

The content of this article comes from bilibili dark horse programmers

2 Create a basic server

const express = require('express')
const router = require('./apiRouter')

const app = express()
app.use(express.json())
app.use(express.urlencoded({
    
     extended: false }))
app.use('/api', router)

app.listen(80, () => {
    
    
  console.log('http://127.0.0.1');
})

3 Write the interface

apiRouter.js

const express = require('express')
const router = express.Router()
// GET 请求
router.get('/get', (req, res) => {
    
    
  const query = req.query
  res.send({
    
    
    status: 0,
    message: 'GET 请求成功',
    data: query
  })
})
// POST 请求
router.post('/post', (req, res) => {
    
    
  const body = req.body
  res.send({
    
    
    status: 0,
    message: 'POST 请求成功',
    data: body
  })
})

module.exports = router

4 cross-domain sharing of cors resources

4.1. Interface cross-domain issues

There are two main solutions to solve the interface cross-domain problem:

  1. CORS (mainstream solution, recommended)
  2. JSONP (flawed solution: only GET requests are supported)

4.2 Use cors middleware to solve cross-domain problems

cors is a third-party middleware for Express. By installing and configuring cors middleware, you can easily solve cross-domain problems.
The steps to use are divided into the following 3 steps:

  1. Run npm install cors to install middleware
  2. Import middleware with const cors = require('cors')
  3. Call app.use(cors()) before routing to configure middleware

4.3 What is CORS

CORS (Cross-Origin Resource Sharing) consists of a series of HTTP response headers, which determine whether the browser prevents the front-end JS code from obtaining resources across domains.
By default, the same-origin security policy of the browser will prevent webpages from "cross-domain" access to resources, but if the interface server is configured with CORS-related HTTP response headers, the browser-side cross-domain access restrictions can be lifted.

4.4 CORS response headers

  1. Access-Control-Allow-Origin: Allow access to the URL of the resource
res.setHeader('Access-Control-Allow-Origin', 'http://www.baidu.com')
res.setHeader('Access-Control-Allow-Origin', '*')
  1. Access-Control-Allow-Headers: Allow sending additional response headers
  • By default, CORS only supports the client sending the following nine request headers to the server:
    Accept, Accept-Language, Content-Language, DPR, Downlink, Save-Data, Viewport-Width, Width, Content-Type (values ​​are limited to one of text/plain, multipart/form-data, application/x-www-form-urlencoded)
  • If the client sends additional request header information to the server, the additional request header needs to be declared on the server side through Access-Control-Allow-Headers, otherwise the request will fail this time
res.setHeader('Access-Control-Allow-Headers', 'Request-Id')
  1. Access-Control-Allow-Methods: Allowed HTTP methods
  • By default, CORS only supports GET POST. HEAD requests initiated by the client
  • If the client wants to request resources from the server through PUT, DELETE, etc., it needs to specify the HTTP method allowed by the actual request through Access-Control-Allow-Methods on the server side
// 只许 POST、GET、DELETE、HEAD 请求方法
res.setHeader('Access-Control-Allow-Methods', 'POST, GET, DELETE, HEAD')
// 允许所有的 HTTP 请求方法
res.setHeader ('Access-Control-Allow-Methods', '*'

4.5 Simple Request

A request that satisfies the following two conditions at the same time is a simple request:

  1. Request method: one of GET , POST , HEAD
  2. HTTP header information does not exceed the following fields: no custom header field, Accept, Accept-Language, Content-language, DPR, Downlink, Save-Data, Viewport-Width, Width, Content-Type (only three values application/x-www-form-urlencoded, multipart/form-data, text/plain)

4.6 Preflight Request

As long as the request meets any of the following conditions, a preflight request is required:

  1. The request method is a request Method type other than GET, POST, or HEAD
  2. The request header contains custom header fields
  3. The data in application/json format is sent to the server
    . Before the browser formally communicates with the server, the browser will first send an OPTION request for pre-checking to know whether the server allows the actual request, so this time the OPTION request is called "pre-checking". ask". After the server successfully responds to the preflight request, the real request will be sent with real data

5 jsonp interface

5.1 The concept and characteristics of JSONP

Concept: The browser <script>requests data on the server through the src attribute of the tag, and the server returns a function call. This way of requesting data is called JSONP
features:

  1. JSONP is not a real Ajax request, because it does not use the XMLHttpRequest object
  2. JSONP only supports GET requests, not POST, PUT, DELETE and other requests

5.2 Create JSONP interface

If CORS cross-domain resource sharing has been configured in the project, in order to prevent conflicts. The ISONP interface must be declared before configuring the CORS middleware. Otherwise,
the JSONP connection will be processed as an interface with CORS enabled

// 优先创建 JSONP 接口【这个接口不会被处理成 CORS 接口】
app.get('/api/jsonp', (req, res) => {
    
    })
// 再配置 CORS 中间件【后续的所有接口,都会坡处理成 CORS 接口】
const cors = require('cors')
app.use(cors())
// 这是一个开启了 CORS 的按口
app.get('/api/get', (req, res) => {
    
    })

Guess you like

Origin blog.csdn.net/weixin_36757282/article/details/128661168