Get into the habit of writing together! This is the 12th day of my participation in the "Nuggets Daily New Plan · April Update Challenge", click to view the details of the event .
cors cross-domain resource sharing
-
Cross-domain issues with interfaces
There is a serious problem in writing GET and POST interfaces: cross-domain requests are not supported
-
Example
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 请求', data:body }) }) module.exports = router 复制代码
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 服务器运行在 http://127.0.0.1.80') }) 复制代码
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(){ 测试 POST 接口 $('#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> 复制代码
When we click the POST button on the web page, the request is not successful, and the terminal will report an error (there is an interface cross-domain problem). Because the web page is opened through the file protocol (
file:///...
), but the requested interface is the http protocol, and there are different protocols. As long as any one of the protocol, domain name, and port number is different, there is a cross-domain problemAccess link:
terminal error
A solution to the problem of interface cross-domain
cors
Mainstream solutions (recommended)jsonp
Flawed solution (only supports GET requests)
Use cors middleware to solve cross-domain problems
-
cors is a third-party middleware of Express. By installing and configuring cors middleware, cross-domain problems can be easily solved
-
The use steps are divided into three steps
- run
npm install cors
install middleware - Use
const cors = require('cors')
import middleware - call
app.use(cors())
configure
- run
-
Example
The above code remains unchanged, only the server-side code needs to be changed, and the cors middleware must be configured before routing to solve the interface cross-domain problem
const express = require('express') const app = express() app.use(express.urlencoded({extended: false})) // 配置 cors 这个中间件 const cors = require('cors') app.use(cors()) const router = require('./apiRouter') app.use('/api', router) app.listen(80, ()=> { console.log('express 服务器运行在 http://127.0.0.1.80') }) 复制代码
Web terminal information