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 ...
- npm install axios
- Create a new html page
- 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
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
, you can see the correct data in the browser
*, which means that multiple sources are not allowed to carry cookies. To carry cookies, you can only write one source
Other cross-domain methods: