外部API的CORS问题-通过PostMan起作用,但与Axios无关的HTTP请求

Lov*_*ock 6 javascript api vue.js axios

正在研究一个涉及汽车数据的新Laravel项目,并找到了免费的查找API。

http://www.carqueryapi.com/documentation/api-usage/
Run Code Online (Sandbox Code Playgroud)

一个示例端点是:

https://www.carqueryapi.com/api/0.3/?callback=?&cmd=getMakes
Run Code Online (Sandbox Code Playgroud)

在具有正常GET请求的PostMan上,这可以正常工作。

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

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

我收到CORS问题:

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Run Code Online (Sandbox Code Playgroud)

有什么我可以做的吗?还是某些API被阻止?

小智 2

您可以使用此修复此错误

    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);
    })
Run Code Online (Sandbox Code Playgroud)

在您的 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;
 }

}
Run Code Online (Sandbox Code Playgroud)

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

 protected $routeMiddleware = [
    'cors' => 'App\Http\Middleware\CORS',
];
Run Code Online (Sandbox Code Playgroud)

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

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