CORS Issue with external API - Works via PostMan but not HTTP request with Axios [duplicate]

两盒软妹~` 提交于 2020-06-14 04:10:06

问题


Working on a new Laravel project that involves car data and found a free look up API.

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

An example endpoint is:

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

This works fine on PostMan with a normal GET request.

However in Vue.js using Axios:

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

I get a CORS issue:

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

Is there anything I can do? Or some the API is blocking?


回答1:


You can fix this error using this

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

And in your api please add a cors Middleware

  <?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;
 }

}

Add Middleware in app\Http\Kernel.php

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

And the you can use this in routes

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


来源:https://stackoverflow.com/questions/42474262/cors-issue-with-external-api-works-via-postman-but-not-http-request-with-axios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!