【问题标题】:405 Error & CORS when making an api request on localhost在 localhost 上发出 api 请求时出现 405 错误和 CORS
【发布时间】:2019-09-16 09:34:09
【问题描述】:

我正在尝试从本地主机环境中的天气 API 提取数据,我收到 405 错误(不允许使用方法)以及“已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:它没有 HTTP ok 状态。”我已经配置了我的标题,但无法弄清楚我做错了什么。它在现场运行良好,但显然这不是一种方便的方式。

我尝试过使用 axios.get 和 axios.post。

var config = {
    headers: {'Access-Control-Allow-Origin': '*'}
};
getWeather: function (){
    axios.get('http://api.openweathermap.org/data/2.5/forecast?id='+ city + '&appid='+ apiKey, config).then((res) => {this.weather = res.data});
}

【问题讨论】:

  • 可以显示错误信息吗?
  • 我认为 chrome 默认会阻止它。试试其他浏览器吧?

标签: laravel vue.js vuejs2 axios


【解决方案1】:

希望添加下面的包会有所帮助

use this https://github.com/barryvdh/laravel-cors

安装:

composer require barryvdh/laravel-cors

服务提供商:

将此Barryvdh\Cors\ServiceProvider::class, 添加到config/app.php

要允许CORS 用于所有路由,请在app/Http/Kernel.php 类的$middleware 属性中添加HandleCors 中间件:

protected $middleware = [
 \Barryvdh\Cors\HandleCors::class,
 // ...
];

注意:确保将其放在所有中间件之前

如果是针对特定中间件,在我们的例子中,它将是api

protected $middlewareGroups = [
'web' => [
   // ...
],

'api' => [
    \Barryvdh\Cors\HandleCors::class, 
    'throttle:60,1',
    'bindings',
],

];

注意:确保将其放在所有中间件之前

发布配置:

php artisan vendor:publish --provider="Barryvdh\Cors\ServiceProvider"

【讨论】:

    猜你喜欢
    • 2014-12-04
    • 2022-01-06
    • 2021-03-02
    • 1970-01-01
    • 2019-09-09
    • 1970-01-01
    • 2015-10-07
    • 2021-12-13
    • 1970-01-01
    相关资源
    最近更新 更多