【问题标题】:CORS Issue with external API - Works via PostMan but not HTTP request with Axios [duplicate]外部 API 的 CORS 问题 - 通过 PostMan 工作,但不适用于 Axios 的 HTTP 请求 [重复]
【发布时间】:2017-07-17 09:19:04
【问题描述】:

从事一个涉及汽车数据的新 Laravel 项目,并找到了一个免费的查找 API。

http://www.carqueryapi.com/documentation/api-usage/

一个示例端点是:

https://www.carqueryapi.com/api/0.3/?callback=?&cmd=getMakes

这在 PostMan 上可以正常 GET 请求。

但是在使用 Axios 的 Vue.js 中:

getAllMakes: function() {
    axios.get("https://www.carqueryapi.com/api/0.3/?callback=?&cmd=getMakes").then(function(response) {
        console.log(response);
    });
}

我遇到了 CORS 问题:

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

有什么我可以做的吗?或者某些 API 被阻塞了?

【问题讨论】:

  • 您需要设置 Access-Control-Allow-Origin 标头。查看此链接以获取更多信息,此页面底部的标题信息:codeheaven.io/how-to-use-axios-as-your-http-client
  • Cors 问题是您的浏览器保护您,这就是为什么它不会在 Postman 中失败,因为他们忽略了它。解决方案是您需要在 Laravel API 中设置正确的标头。有几种方法可以解决这个问题,请参阅stackoverflow.com/questions/33076705/…
  • @tam5:他在示例代码中使用的是 Vue 而不是 Laravel。我个人认为出于安全原因,您应该在服务器端而不是在客户端获取 API 数据。也许这个演示 api 不需要凭据,但我相信稍后如果您想获取真实数据,您将需要针对 api 进行身份验证。然后问题是:您是否要让用户控制身份验证凭据?如果没有在后端获取数据,然后在您的 vue 组件中从那里获取它。

标签: javascript api vue.js axios


【解决方案1】:

您可以使用此修复此错误

    return axios(url, {
      method: 'GET',
      mode: 'no-cors',
      headers: {
        'Access-Control-Allow-Origin': '*',
        'Content-Type': 'application/json',
      },
     credentials: 'same-origin',
    }).then(response => {
      console.log(response);
    })

请在您的 API 中添加一个 cors 中间件

  <?php
 namespace App\Http\Middleware;

 use Closure;

class CORS {

/**
 * Handle an incoming request.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Closure  $next
 * @return mixed
 */
public function handle($request, Closure $next)
{

    header("Access-Control-Allow-Origin: *");

    // ALLOW OPTIONS METHOD
    $headers = [
        'Access-Control-Allow-Methods'=> 'POST, GET, OPTIONS, PUT, DELETE',
        'Access-Control-Allow-Headers'=> 'Content-Type, X-Auth-Token, Origin'
    ];
    if($request->getMethod() == "OPTIONS") {
        // The client-side application can set only headers allowed in Access-Control-Allow-Headers
        return Response::make('OK', 200, $headers);
    }

    $response = $next($request);
    foreach($headers as $key => $value)
        $response->header($key, $value);
    return $response;
 }

}

在app\Http\Kernel.php 中添加中间件

 protected $routeMiddleware = [
    'cors' => 'App\Http\Middleware\CORS',
];

然后你可以在路由中使用它

Route::get('/', function () {`enter code here`
})->middleware('cors');

【讨论】:

    猜你喜欢
    • 2021-10-04
    • 2020-07-19
    • 2018-06-22
    • 1970-01-01
    • 2016-07-03
    • 1970-01-01
    • 2018-08-27
    • 2020-07-21
    • 1970-01-01
    相关资源
    最近更新 更多