vendredi 29 juin 2018

Custom request headers cause CORS

In my project, my custom header cause CORS and when I remove it from request headers, everything works truly.

Laravel is my back-end and I send requests with axios.

Here is my middleware to add CORS headers to response,

 public function handle($request, Closure $next)
    {
        $response = $next($request);
        $response->header('Access-Control-Allow-Credentials', 'true');
        $response->header('Access-Control-Allow-Origin', '*');
        $response->header('Access-Control-Allow-Methods', 'OPTIONS, GET, POST, PATCH, PUT, DELETE');
        $response->header('Access-Control-Allow-Headers', 'Auth-Type, X-API-KEY, Origin, Content-Type, Accept, Authorization');

        return $response;
    }

Auth-Type is my custom header and my front-end request is like,

function getCities(data) {
    return axios({
        method: 'get',
        url: appConstants.BASE_URL + '/city/query',
        headers: {
            'Content-Type': 'application/json',
            'Auth-Type': 'admin'
        },
        params: data
    });
}

When I send the request containing Auth-Type, Chrome log me an error like:

Failed to load http://example.com/api/v1/city/query: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 405.

As you seen in my CORS middleware, I added Auth-Type as my allowed headers in Access-Control-Allow-Headers. Also in this situation (I mean custom headers passing), the get method converts to OPTIONS.

Any solutions will appreciate.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2Mska28
via IFTTT

Aucun commentaire:

Enregistrer un commentaire