vue.js - 添加自定义标头Vue时请求失败
问题描述
我正在向 Axios 发出请求,但是在添加自定义标头时失败(API 需要自定义标头)。如果添加自定义标头,则响应为:
has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
在 API 中启用了 CORS
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-
Type, Accept, Access-Control-Request-Method,t-id-establecimiento,bt-
username,bt-nombre-empleado,ipaddress");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
header("Allow: GET, POST, OPTIONS, PUT, DELETE");
我在 Vue 中的要求:
let headers = this.getHeader()
this.$http(`${mUrl}`,{headers})
.then(function (resp) {
console.log(resp.data)
})
.catch(function (err) {
console.log('rerrrr' + err)
})
我的自定义标题:
{
'Authorization': "Bearer " + urlParams.get('token'),
'Content-Type': 'application/json',
'bt-id-establecimiento': urlParams.get('bt-id-establecimiento'),
'bt-username': urlParams.get('bt-username'),
'bt-nombre-empleado': urlParams.get('bt-nombre-empleado'),
'ipaddress': urlParams.get('ipaddress'),
}
解决方案
在处理 CORS 错误时,大多数时候您不需要修改请求标头。99% 的时间,问题出在后端。确保允许 CORS:
- 服务器配置和
- 应用
如果您使用 XAMPP 或任何 Apache 服务器,默认情况下不启用 CORS。尽管您已经在应用程序上允许了 CORS,但它仍然会被服务器阻止。
注意:更改配置文件时请务必重启服务器
推荐阅读
- java - 测量每个线程的精确执行时间
- javascript - 如何在 SharePoint 中禁用刻度控制
- oracle - 如何编写一个接受可变数量绑定参数的存储过程
- python - 如何使用python从(nifti文件).nii.gz文件中获取.json文件
- mysql - 如果列为空,Mysql concat 不起作用,查询有什么问题?
- javascript - 获取控制台日志错误代码 selenium js
- r - 如何在矩阵上循环操作?
- javascript - 大型 mailto 链接无法在 Chrome 中打开
- javascript - 当我们提到(@)机器人时,如何使 Discord.js 机器人响应本地图片?
- r - 按名称减去数据框的列