一.问题描述 & 解决思路
起因:删除用户按钮在写了 @click 属性后无法正常调用。
第一步
怀疑是后端接口没写对。遂用ApiPost执行了一个删除操作:
发现后端 API 没问题。
第二步
怀疑 axios 执行 delete 请求出错。把
const res = await this.$http.delete(
user/${id})
的res
打印出来发现提示:“没有token”。
找到 axios 的请求拦截器配置,在 main.js 里面添加配置
axios.interceptors.request.use(config=> {
config.headers.Authorization = `Bearer ${window.sessionStorage.getItem('token')}`
return config
})
为 delete 报文添加一个 key 为“Authorization”的首部,value 为 "Bearer <token>"
第三步
此时的新问题是用户列表又加载不出来了,显示 no data.并且报错:
has been blocked by CORS policy: Request header field authorization is not allowed by Access-Control-Allow-Headers in preflight response.
看来后台的 Cors 中间件不允许authorization通过,遂在Cors中间件中添加
问题解决。
补充
在使用 Ant 上传组件时出现了类似的问题。即 API 工具上传文件成功,在前端 UI 上传失败。控制台报错为:
has been blocked by CORS policy:
Request header field x-requested-with is not allowed by Access-Control-Allow-Headers in preflight response.
在后端的中间件中补充该首部即可: