跨域请求
nodejs后台配置的两种方案(响应时)
1. res.setHeader(‘Access-Control-Allow-Origin’, req.headers.origin); 允许跨越
2. cors 中间件 (如果后端配置了中间件,前端不需要设置请求头)
需求:服务器跨域给前端写cookie
//cors中间件
var cors = require('cors');
app.use(cors({
"origin": "*",
"methods": "GET,HEAD,PUT,PATCH,POST,DELETE",
"preflightContinue": false,
"optionsSuccessStatus": 204
}));
跨源凭据:
ajax跨源请求不提供凭据(cookie、HTTP认证及客户端SSL证明等)
前端:设置ajax的请求带凭据
withCredentials=true
后端:接受后http必须做出对应的响应:
Access-Control-Allow-Credentials: true
nodejs:
router.get('/cookies', function(req, res){
res.setHeader('Access-Control-Allow-Origin',
req.headers.origin); //允许跨越
res.setHeader('Access-Control-Allow-Origin', '*'); //允许所有跨越
res.setHeader('Access-Control-Allow-Credentials', true);//告诉客户端可以在HTTP请求中带上Cookie(凭证数据),客户端可以不带
}
前端原生:请求头里面带凭证,带cookie
var xhr = new XMLHttpRequest();
xhr.open("post", "xxx/xxx", true);
xhr.withCredentials = true; //放在 open 方法后面比较靠谱
xhr.onload = function(){}
xhr.send("a=1&b=2");
前端jqAjax: 请求头里面带凭证,带cookie
$.ajax({
type:'get',
url:"http://localhost:3000/logouts",
dataType:"json",
xhrFields: {
withCredentials: true
},
success:function(data){
console.log(data);
}
})
前端:axios 请求头里面带凭证,带cookie
axios.defaults.withCredentials=true
前端:fetch 请求头里面带凭证,带cookie
fetch('http:localhost:3000/cookies', {
credentials: 'include', //凭证
method:'get',
headers:{
'Accept':'application/json,text/plain,*/*',
'Content-type':'application/x-www-form-urlencoded;charset=utf-8'
},
body:数 据
}).then(function(res) {
// ...
})