Make writing a habit together! This is the 12th day of my participation in the “Gold Digging Day New Plan · April More text Challenge”. Click here for more details.

Cors cross-domain resource sharing

  • Cross-domain problems with interfaces

    There is a serious problem with writing GET and POST interfaces: cross-domain requests are not supported

  • The sample

    Routing module

    const express = require('express')
    const router = express.Router()
     
    router.post('/post'.(req, res) = >{
        const body = req.body
            res.send({
            status:0.msg:'POST request'.data:body
        })
    })
    module.exports = router
    Copy the code

    Server-side code

    const express = require('express')
    const app = express()
    
    app.use(express.urlencoded({extended: false}))
    
    const router = require('./apiRouter')
    app.use('/api', router)
    
    app.listen(80.() = > {
        console.log('Express server running at http://127.0.0.1.80')})Copy the code

    Test 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 > < script SRC = "https://cdn.staticfile.org/jquery/1.10.0/jquery.min.js" > < / script > < / head > < body > < button id = "postBut" > POST < / button > < script > $(function () {test POST interface $(' # postBut) on (' click ', function () {$. Ajax ({type: "POST", Url: 'http://127.0.0.1/api/post' data: {name: 'haimeimei, age: 18}, success: function(res){ console.log(res) } }) }) }) </script> </body> </html>Copy the code

    When we click the POST button in the web page, the request is not successful, the terminal will report an error (there is a cross-domain interface problem). Because the web page is through file protocol (file:///…) Open web page, but the request interface is HTTP protocol, there are different protocols. As long as any protocol, domain name, port number is different, there is a cross – domain problem

    Access link:

    Terminal error


Solution to interface cross – domain problem

  • corsMainstream solutions (recommended)
  • jsonpFlawed solution (support GET requests only)

Use CORS middleware to solve cross-domain problems

  • Cors is a third-party middleware for Express. You can easily solve cross-domain problems by installing and configuring CORS middleware

  • The procedure is divided into three steps

    • runnpm install corsInstalling middleware
    • useconst cors = require('cors')Import middleware
    • Called before routingapp.use(cors())Configuring middleware
  • The sample

    The above code remains unchanged, only the server-side code needs to be changed, and cORS middleware must be configured before routing to solve the cross-domain interface problem

     const express = require('express')
     const app = express()
     
     app.use(express.urlencoded({extended: false}))
     
     // Configure cORS middleware
     const cors = require('cors')
     app.use(cors())
     
     const router = require('./apiRouter')
     app.use('/api', router)
     
     app.listen(80.() = > {
         console.log('Express server running at http://127.0.0.1.80')})Copy the code

    Web terminal information