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?
The CORS standard is a client-side standard, implemented in the browser. So it is the browser which prevent the call from completing and generates the error message - not the server. Postman does not implement the CORS restrictions, which is why you don't see the same error when making the same call from Postman.
In essence how to you make POSTMAN behave like a browser because we need to test to make sure our APIs are configure correctly. So what if the API works from POSTMAN and it breaks due to CORS from the browser. It means the API is useless.
To get rid of a CORS error, you can download a browser extension like CORS Unblock ↗. The extension appends Access-Control-Allow-Origin: * to every HTTP response when it is enabled. It can also add custom Access-Control-Allow-Origin and Access-Control-Allow-Methods headers to the responses.
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);
})
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',
];
Then you can use this in routes
Route::get('/', function () {`enter code here`
})->middleware('cors');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With