I'm using a Vue.JS application that is calling an API built with Lumen. I'm always getting the below error whenever the Vue.JS app calls the Lumen API.
Below is a middleware used for CORS in Lumen.
<?php
namespace App\Http\Middleware;
use Closure;
class CorsMiddleware
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
//Intercepts OPTIONS requests
if($request->isMethod('OPTIONS')) {
$response = response('', 200);
} else {
// Pass the request to the next middleware
$response = $next($request);
}
// Adds headers to the response
$response->header('Access-Control-Allow-Methods', 'HEAD, GET, POST, PUT, PATCH, DELETE');
$response->header('Access-Control-Allow-Headers', $request->header('Access-Control-Request-Headers'));
$response->header('Access-Control-Allow-Origin', '*');
// Sends it
return $response;
}
}
I have this added in the .htaccess file of lumen in public folder
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "*"
</IfModule>
UPDATE 1 the ajax request header from chrome's network tab:-
I'm using:
PHP Version: 5.6
Development Environment: Homestead (Apache)
*, *
but it should be only a single asterisk. Is the response header somewhere else modified? You should also never use an asterisk in production, except when you want to allow every website to make calls to your API. - ssc-hrep3Network
tab in the Chrome DevTools, then click onto the request and on the tabHeaders
you'll see theResponse Headers
. The headerAccess-Control-Allow-Origin
should be a single value: either*
orhttps://yourdomain.com
. It seems like this value is set to*, *
somewhere in the back-end. It might be that setting the header in the.htaccess
file and also in PHP leads to this invalid comma-separated header. You need to fix this, then it should be working. - ssc-hrep3