laravel - 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');
});
}
},
我已经作曲家转储了,没有任何影响解决问题。我做错了什么吗?这个问题有什么解决方案吗?提前致谢!
解决方案
这里的问题似乎是 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');
});
希望这会有所帮助,祝你好运!
推荐阅读
- javascript - 来自 SQS 队列的异步回调不会从队列中删除项目
- javascript - 如何在正则表达式中转义双斜杠(javascript)
- ios - Unity 使用 Apple 刷新令牌登录
- java - Web 服务模板:如何在 Web 服务模板中传递标头
- http - MC60 HTTP GET 请求问题
- mysql - 在单个 sql 查询中分组和计数
- excel - 工作表受保护时运行时错误 1004
- firefox - Firefox 标签中带下划线的标题
- .net-core - Autofac 多个注册到单个服务。简单注入器 -> Autofac 翻译
- r - 如何根据 mlr3 中的指标列和批量训练预测对任务进行子集化?