首页 > 解决方案 > CORS 策略已阻止从源对 X 的 XMLHttpRequest 的 CORS 访问

问题描述

CORS 对 X 来源的 XMLHttpRequest 的访问已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:它没有 HTTP ok 状态。

嗨,我正在努力解决 CORS 拒绝我的 Vue 组件与带有 axios 的外部 API 交互的问题,因为它返回此错误。我已经尝试过使用 Barryvdh 的 Cors 标头支持并制作中间件和自定义路由。它根本行不通。Barryvdh 的 repo 中的 README.md 中提到的所有内容都已完成,不幸的是,这个问题不会以任何必要的方式得到解决。

这是代码,尽管我认为不需要显示,因为它与 repo 中提到的完全相同;

在 Kernel.php 中:

protected $middleware = [
    \Barryvdh\Cors\HandleCors::class,
inside app.php (providers array):

Barryvdh\Cors\ServiceProvider::class,

配置/cors.php:

'supportsCredentials' => false,
'allowedOrigins' => ['*'],
'allowedHeaders' => ['*'],
'allowedMethods' => ['*'], // ex: ['GET', 'POST', 'PUT',  'DELETE']
'exposedHeaders' => [],
'maxAge' => 0,

这是 axios 的调用(我已将我的令牌替换为“令牌”)

    methods: {
        loadWeatherData: function() {
            axios.get( 'http://api.openweathermap.org/data/2.5/weather?q=London&mode=json&units=metric&appid=TOKEN' )
                .then( function( response ) {
                    console.log( 'radi' );
            }).catch( errors => {
                console.log( errors+' ne radi');
            });
        }
    },

我已经作曲家转储了,没有任何影响解决问题。我做错了什么吗?这个问题有什么解决方案吗?提前致谢!

标签: laravelvue.jscorsaxios

解决方案


这里的问题似乎是 axios 喜欢发送自己的默认标头,而这些标头没有通过您的外部请求的预检。要解决此问题,您需要删除有问题的标头。

我能够重新创建您的错误,并使用下面的代码绕过 CORS 问题。

let url = 'https://api.openweathermap.org/data/2.5/weather?q=London&mode=json&units=metric&appid=TOKEN';

// create a new instance so we don't delete the headers for other requests
let instance = axios.create();

// delete headers if existing
delete instance.defaults.headers.common['Accept'];
delete instance.defaults.headers.common['X-Requested-With'];
delete instance.defaults.headers.common['X-CSRF-TOKEN'];

// use the new axios instance to make your get request
instance.get(url)
    .then(function(response) {
        console.log(response);
    }).catch( errors => {
        console.log(errors + ' ne radi');
    });

希望这会有所帮助,祝你好运!


推荐阅读