本文介绍了Axios返回请求标头字段X-Requested-With是Access-Control-Allow-Headers不允许的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a Laravel app in which I use axios in a VueJS component to send GET requests to an external public API upon clicking a button, but it throws these error:

[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)

这是我失败的尝试:

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

我只是应该收到一些Chuck Norris的笑话,以便在控制台上打印...

I just should receive some Chuck Norris jokes to print on the console...

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

PS: I've seen some facts relative to CORS but I didn't get anything out of it, so here I am.

推荐答案

Laravel使用标头来确定请求是XHR还是常规请求.

Laravel uses a header to be able to determine wether a request was XHR or a normal request.

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

In the source code of Laravel you can see the Request::ajax() method, which calls the isXmlHttpRequest() method from Symfony.

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

The only issue with this is that CORS doesn't really like such headers.

如果要删除它,请检查 resources/js 中的 bootstrap.js 并再次编译资产.

If you want to remove it, check bootstrap.js in resources/js and compile your assets again.

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

Another solution would be to delete the header just before the call:

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

这篇关于Axios返回请求标头字段X-Requested-With是Access-Control-Allow-Headers不允许的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 18:32