axios返回Request头域 X-Requested-With is not allowed by Access-Control-Allow-Headers

Dan*_*ani 1 laravel vue.js axios

我有一个 Laravel 应用程序,其中我在 VueJS 组件中使用 axios 在单击按钮时将 GET 请求发送到外部公共 API,但它会引发以下错误:

[Error] Request header field X-Requested-With is not allowed by Access-Control-Allow-Headers.
[Error] XMLHttpRequest cannot load http://api.icndb.com/jokes/random due to access control checks.
[Error] Failed to load resource: Request header field X-Requested-With is not allowed by Access-Control-Allow-Headers. (random, line 0)
Run Code Online (Sandbox Code Playgroud)

这是我失败的尝试:

const url = "http://api.icndb.com/jokes/random";
const response = await axios.get(url);
Run Code Online (Sandbox Code Playgroud)

我只是应该收到一些查克·诺里斯的笑话并打印在控制台上......

PS:我已经看到了一些与 CORS 相关的事实,但我没有从中得到任何信息,所以我就在这里。

Dou*_*aan 5

Laravel 使用标头来确定请求是 XHR 还是普通请求。

在 Laravel 的源代码中你可以看到该Request::ajax()方法,它调用了isXmlHttpRequest()Symfony 中的方法。

唯一的问题是 CORS 并不真正喜欢这样的标头。

如果您想删除它,请重新签bootstrap.jsresources/js并编译您的资产。

另一个解决方案是在调用之前删除标头:

delete axios.defaults.headers.common['X-Requested-With'];