在 axios 中响应代码 400 时出现问题

Posted

技术标签:

【中文标题】在 axios 中响应代码 400 时出现问题【英文标题】:Something wrong when response with code 400 in axios 【发布时间】: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 在一个非常相似的问题上。 【参考方案1】:

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

【讨论】:

【参考方案2】:

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

【讨论】:

以上是关于在 axios 中响应代码 400 时出现问题的主要内容,如果未能解决你的问题,请参考以下文章