首页 > 解决方案 > 添加自定义标头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.

我已经看到提出了两个请求:1-第一个请求: 第一个请求

2- 第二次请求 第二个请求

在 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'),

}

标签: vue.jsrequestfetch

解决方案


在处理 CORS 错误时,大多数时候您不需要修改请求标头。99% 的时间,问题出在后端。确保允许 CORS:

  • 服务器配置和
  • 应用

如果您使用 XAMPP 或任何 Apache 服务器,默认情况下不启用 CORS。尽管您已经在应用程序上允许了 CORS,但它仍然会被服务器阻止。

注意:更改配置文件时请务必重启服务器


推荐阅读