解决方法
async test() {
console.log(this.jwttoken);
await this.$axios({
method: "post",
url: '/home',//这里的地址已提前通过main.js提前配置默认路径
responseType: "blob",//这里是指定服务器返回给我们的数据类型的可以不写
headers: { Authorization: this.jwttoken },
}).then(function (value) {
console.log(value.data);
});
},
修改后可能出现的问题
Access to XMLHttpRequest at 'http://localhost:4040/home' from origin 'http://localhost:8080' has been blocked by CORS policy: Request header field authorization is not allowed by Access-Control-Allow-Headers in preflight response.
原因在于后端没有配置好跨域策略,这里我引用的是'cors'。
npm i cors//通过npm在服务器端下载cors
// 加载cors,配置跨域资源共享
const cors = require('cors')
//挂载至服务器
app.use(cors())
问题起因
本次问题起源于在为vue前端设置发起post请求,因为jwt身份认证机制需要携带jwttoken在响应头中,但在两次测试中前端的请求均被后端expressJwt组件过滤
//前端post请求代码
async test() {
await this.$axios
.post("/home", {
headers: {
//头部参数
"Authorization":this.jwttoken,
},
})
.then(function (value) {
console.log(value.data);
});
},
此时后端打印的响应头为
{
host: 'localhost:4040',
connection: 'keep-alive',
accept: '*/*',
'access-control-request-method': 'POST',
'access-control-request-headers': 'content-type',
origin: 'http://localhost:8080',
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36 Edg/117.0.2045.47',
'sec-fetch-mode': 'cors',
'sec-fetch-site': 'same-site',
'sec-fetch-dest': 'empty',
referer: 'http://localhost:8080/',
'accept-encoding': 'gzip, deflate, br',
'accept-language': 'zh-CN,zh;q=0.9'
}
{
host: 'localhost:4040',
connection: 'keep-alive',
'content-length': '194',
'sec-ch-ua': '"Microsoft Edge";v="117", "Not;A=Brand";v="8", "Chromium";v="117"',
accept: 'application/json, text/plain, */*',
'content-type': 'application/json',
'sec-ch-ua-mobile': '?0',
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36 Edg/117.0.2045.47',
'sec-ch-ua-platform': '"Windows"',
origin: 'http://localhost:8080',
'sec-fetch-site': 'same-site',
'sec-fetch-mode': 'cors',
'sec-fetch-dest': 'empty',
referer: 'http://localhost:8080/',
'accept-encoding': 'gzip, deflate, br',
'accept-language': 'zh-CN,zh;q=0.9'
}
可以看到并不存在我们设置的token,此时我们使用postmen对端口进行测试
此时我们再查看服务器打印的信息,可以清楚的看到我们发起的token
{
authorization: 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImFkbWluMSIsImlhdCI6MTY5NjE0NTg0MiwiZXhwIjoxNjk2MjMyMjQyfQ.CS9h-0Ps-EKTVuSXChexfD7UHANqv4FjY9KTA7WinhI',
'user-agent': 'PostmanRuntime/7.33.0',
accept: '*/*',
'postman-token': '40f41e4d-9d15-4f36-a12f-3acf02429581',
host: '127.0.0.1:4040',
'accept-encoding': 'gzip, deflate, br',
connection: 'keep-alive',
'content-length': '0'
}
问题所在
因此我们可以分析出原因==》我们使用的设置的请求头并不在发起的post请求头中