跨域問題可以參考阮一峰的博客,講的很詳細(xì)。
跨域資源共享 CORS 詳解
這里記錄一下,node.js服務(wù)端和axios/ajax請求的實(shí)踐代碼。
node.js
//以express為例
//設(shè)置跨域訪問
app.all('*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Content-Type");
res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");;
next();
});
axios
get: 常規(guī)操作
post: 需要將post data轉(zhuǎn)化成文本,否則content-type: application/json,跨域成非簡單請求,進(jìn)入預(yù)檢請求。會增加一次HTTP查詢請求。axios的一個(gè)bug. axios issues362
//get
axios.get('http://127.0.0.1:8081/getJson')
.then(res=>{
console.log(res);
})
.catch(err=>{
console.log(err);
})
//post
//user JSON.stringify or other libs like qs.stringify
let data=JSON.stringify({
data:'axios',
info:{
type:'post',
}
})
axios.post('http://127.0.0.1:8081/postJson',data)
.then(res=>{
console.log(res);
})
.catch(err=>{
console.log(err);
})
ajax
正常操作即可
//get
$.get('http://127.0.0.1:8081/getJson',(data,status)=>{
console.log(status);
console.log(data);
})
//post
//跨域請求post
$.post('http://127.0.0.1:8081/postJson',{
data:'ajax',
info:{
data:'post',
}
},(data,status)=>{
console.log(status);
console.log(data);
})