外部API的CORS问题 - 通过PostMan工作,但不是Axios

时间:2017-02-26 21:06:06

标签: api vue.js axios

处理涉及汽车数据的新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阻止?

1 个答案:

答案 0 :(得分:0)

您可以使用此方法解决此错误

    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');