Search code examples
laravelvue.jscorsaxiosvuex

Vuex Axios CORS Block Acess-control-allow-origin


This is the error:

enter image description here

So, I make sure my backend API sends the acess-control-allow-origin header:

uex

This my axios code:

     loadTopSales ({ commit }) {
       axios
         .get('http://tms.test/api/top-sales', {
           headers: {
             'Access-Control-Allow-Origin': '*',
             Accept: 'application/json',
         Authorization: 'Bearer ' + this.state.token,
             withCredentials: true
           }
         })
         .then(items => {
           commit('SET_TOP_SALES', items)
           console.log(items)
         })
         .catch(err => {
           console.log(err)
         })
     }

Please, help me. I've tried every question in stackoverflow

Check curl -v -x options

enter image description here

My backend set header

 public function handle($request, Closure $next)
    {
        $headers = [
            'Access-Control-Allow-Origin' => '*',
            'Access-Control-Allow-Methods' => 'PUT,POST,GET,OPTIONS,ORIGIN',
            'Access-Control-Allow-Headers' => 'Accept,Authorization,Content-Type,Origin,X-Auth-Token',
            'Access-Control-Allow-Credentials' => 'true',
        ];
        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;
    }

enter image description here

This my answer I config CORS in iis

<httpProtocol>
    <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept,Authorization" />
        <add name="Access-Control-Allow-Methods" value="GET, PUT, POST, HEAD, OPTIONS" />
        <add name="Access-Control-Allow-Credentials" value="true" />
    </customHeaders>
</httpProtocol>

enter image description here


Solution

  • Seems like the API doesn't handle CORS preflight requests. It should return Access-Control-Allow-Origin header for OPTIONS method as well (alongside Access-Control-Allow-Methods) with 204 No Content.

    You can check it with curl -v -X OPTIONS http://tms.test/api/top-sale.