用 vue 作了一个前端系统,后端用 node.js + express。开始用 session 作为登录态,但因为有些情况最后放弃,直接改为 JWT。这个的笔记下回再写。
……很长时间后,碰到一个问题,就是后端老是拿不到 axios 数据。
而且 get 请求变成 OPTIONS。找了很久,找到了答案:
// 自定义跨域中间件
const allowCors = function(req, res, next) {
res.header('Access-Control-Allow-Origin', '前端应用域名');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type, authorization');
res.header('Access-Control-Allow-Credentials', 'true');
next();
};
app.use(allowCors); //使用跨域中间件即在后端服务器里加上面那行。我用 express 直接生成的代码,在根目录下的 app.js 进行修改。
此时,就出现难点……
找了很久,也有很多答案,但试过后都无效,并不能解决问题。
最后在 axios 的发起端解决问题:
axios.get('请求URL', {
Headers: {
'content-type': 'application/x-www-form-urlencoded',
'authorization': Token
},
params: {
param1: 'string',
param2: 'string'
}
}).then(res => {
console.log(res.data)
}).catch(err=>{
console.log(err)
})只是修改了写法:
axios({
method: 'get',
url: '请求URL',
headers: {
'content-type': 'application/x-www-form-urlencoded',
'authorization': Token
}
}).then(res => {
console.log(res.data)
}).catch(err=>{
console.log(err)
})此时,后端就拿到了 headers 里的 authorization。