【问题标题】:Something wrong when response with code 400 in axios在 axios 中响应代码 400 时出现问题
【发布时间】:2018-10-12 11:44:01
【问题描述】:

我正在使用 Vue 和 Axios 构建一个 SPA 前端。当服务器在 CROS 中发送带有代码 400 的响应时。浏览器的控制台日志:

(2) POST http://dev.sportx.one/api/token/ 400 (Bad Request) **This line logged twice**
Failed to load http://dev.sportx.one/api/token/: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access. The response had HTTP status code 400.
Error: Network Error
    at e.exports (spread.js:25)
    at XMLHttpRequest.l.onerror (spread.js:25)

我如何发送请求:

api.request({
 url: '/api/token/',
  method: 'post',
  data: {
    email: '972372527@qq.com',
    password: 'aaaaaaaA'
  }
}).catch(err=>{console.log(err)})

浏览器的网络检查器显示 2 个请求(OPTIONS 和 POST)已发送。他们俩都按预期工作。

如果服务器发送 20X 响应而没有任何错误捕获。一切都很好。

我在新的 html 文件中尝试相同的代码,并且只加载 axios 的脚本文件。遇到同样的错误。

【问题讨论】:

  • 检查 400 错误响应中是否启用了 CORS(Access-Control-Allow-Origin 设置为 *)。如果您使用的是 Laravel,我注意到发生错误时不会发送 CORS 标头。
  • @lkbel 我确定标题设置正确。
  • 后端不应以 400 错误代码响应 OPTION 飞行前请求。
  • Answer I wrote 在一个非常相似的问题上。

标签: javascript vue.js cors axios


【解决方案1】:

预检请求不应响应 400 错误。

【讨论】:

    【解决方案2】:

    你需要设置 'Access-Control-Allow-Origin': '*'

    【讨论】:

      猜你喜欢
      • 2018-12-26
      • 2021-11-08
      • 1970-01-01
      • 1970-01-01
      • 2016-08-29
      • 2020-11-20
      • 1970-01-01
      • 2015-09-04
      • 1970-01-01
      相关资源
      最近更新 更多