CORS与外部API的问题 - 通过Postman起作用,但与AXIOS不使用HTTP请求



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

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

示例端点是:

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

这在正常的获取请求上对邮递员来说正常工作。

但是,在vue.js中使用Axios:

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阻止?

您可以使用此

来修复此错误
    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 AppHttpMiddleware;
 use Closure;
class CORS {
/**
 * Handle an incoming request.
 *
 * @param  IlluminateHttpRequest  $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' => 'AppHttpMiddlewareCORS',
];

然后您可以在路线中使用此

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

相关内容

最新更新