CORS cross-domain resource sharing

Cross-domain-non-same-origin policy request The
protocol domain name and port number are the same as the same source. One difference is cross-domain

Front-end processing using axios.js request ...

  1. npm install axios
  2. Create a new html page
  3. Introduce axios on this page and make a request
axios.get('http://localhost:8001/').then(result=>{
    console.log(result)
})

Backend processing

I wrote two ports one for http service and one for port service

let express = require('express')

// 8000 端口服务 作为当前目录http服务
let app = express()
app.use(express.static(__dirname))
app.listen(8000)

// 8001 端口的服务 返回数据
var app2 = express();
app2.listen(8001,()=>{
    console.log('okk')
})

app2.get('/',(req,res)=>{
    res.send('获取成功')
})

Terminal input node server to start the service
. Error
Insert picture description here
processing occurs in the browser console. Cross-domain.
Normally add
res.header("Access-Control-Allow-Headers","*")
it under the port to solve
it. Here I write all together

var allowCrossDomain = (req,res,next)=>{
    // 控制请求源 
    res.header("Access-Control-Allow-Origin","*"); //res.header("Access-Control-Allow-Origin","http://localhost:8000");
    res.header("Access-Control-Allow-Credentials",true);
    // 请求头 带token
    res.header("Access-Control-Allow-Headers","*") //res.header("Access-Control-Allow-Headers","Content-Type,Content-Length,Authorization,Accept,X-Requested-With")
    // 允许请求的方法 get post put del
    res.header("Access-Control-Allow-Methods","*") //res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,HEAD,OPTIONS")
    if(req.method === 'OPTIONS'){
      res.send('ok');
      return;
    }
    next()
}
app2.use(allowCrossDomain)

Restart the service
Insert picture description here
, you can see the correct data in the browser
Insert picture description here
*, which means that multiple sources are not allowed to carry cookies. To carry cookies, you can only write one source

Other cross-domain methods:

JSONP and JQuery implement cross-domain

http proxy proxy

Published 41 original articles · Likes2 · Visits 1836

Guess you like

Origin blog.csdn.net/weixin_43883485/article/details/104784837