问题
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