跨域請求
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) {
// ...
})