今天一直在練習(xí)如何使用Vue
,就把自己之前用node
寫的個(gè)人博客改改,拿來當(dāng)接口,涉及到跨域請(qǐng)求的問題,接下來簡(jiǎn)單的說下自己所遇到的問題,和解決方法。
一. 用cors來實(shí)現(xiàn)跨域請(qǐng)求:
一想到跨域請(qǐng)求,腦子里首先出現(xiàn)的是jsonp
,但是jsonp
只能是get
請(qǐng)求,在向后臺(tái)提交數(shù)據(jù)時(shí)顯然用ge
t是不合適的,所以選擇用cors
,用cors
時(shí)后臺(tái)要實(shí)現(xiàn)相關(guān)的配置,如下:
var app = express(); //express框架
//設(shè)置跨域訪問
app.all('*', function(req, res, next) {
res.header('Access-Control-Allow-Origin', "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
res.header("X-Powered-By",' 3.2.1');
res.header("Content-Type", "application/json;charset=utf-8");
next();
});
上面的設(shè)置就不一一解釋了,我想根據(jù)每個(gè)字段的值,應(yīng)該都知道是干什么的,特別強(qiáng)調(diào)下:res.header('Access-Control-Allow-Origin', "*");
,這樣設(shè)置允許所有的域,如果將*
號(hào)改為指定的域,則表明只允許特定的域。
二. 如何來存session?
因?yàn)槲矣玫氖?code>vue-resource插件,所以在每次跨域請(qǐng)求后臺(tái)時(shí)都是一個(gè)新的session
,那么如何來保存我們的session呢?當(dāng)然是要打開cookie了,這樣才能保證每次的session都不是新的。
了解cors
的都知道,在后臺(tái)如果要允許提交cookie
的話,要設(shè)置:Access-Control-Allow-Credentials:true
,這樣后端才會(huì)接收前端發(fā)來的cookie
,所以將后臺(tái)的跨域請(qǐng)求設(shè)置改一下就行了:
//將外源設(shè)為指定的域,比如:http://localhost:8080
res.header('Access-Control-Allow-Origin', "http://localhost:8080");
//將Access-Control-Allow-Credentials設(shè)為true
res.header('Access-Control-Allow-Credentials', true);
當(dāng)然只允許后臺(tái)接收cookie是不夠的,必須得有人發(fā)送cookie啊,所以前端的請(qǐng)求頭信息也是要變的,加上:withCredentials: true
就可以了。
以用戶登錄為例:
submit: function (){
this.$http.post(this.url, {
username: this.username,
userpass: this.userpass
},{
withCredentials: true //打開cookie
}).then( res => {
console.log(res);
if (res.body.result == 'ok'){
this.$router.push({path: '/home'});
}
}).catch( error => {
console.log(error);
});
}
就這樣簡(jiǎn)單的設(shè)置一下就可以了,這也是第一次對(duì)cors的應(yīng)用,希望對(duì)初學(xué)的你也有幫助!