A
A
Alexander2017-01-30 18:11:54
Angular
Alexander, 2017-01-30 18:11:54

How to fix No 'Access-Control-Allow-Origin'?

I am writing a SPA application. I assembled the project through webpack on the angular 2 off.doc. I send a simple post request and this is what the console outputs:

XMLHttpRequest cannot load http://spa.local/api/heroes. 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:1313' is therefore not allowed access.
hero.service.ts?e399:46 0 -  {"isTrusted":true}

Created CORS middleware:
class Cors
{
    public function handle($request, Closure $next)
    {
        return $next($request)
            ->header('Access-Control-Allow-Origin', '*')
            ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
            ->header('Access-Control-Max-Age', '1000')
            ->header('Access-Control-Allow-Headers', 'Origin, Content-Type, X-Auth-Token');
    }
}

But the error is still the same.
I make a post request via POSTMAN , everything is fine, the server responds with data. I look in the headers tab:
Access-Control-Allow-Headers →Origin, Content-Type, X-Auth-Token
Access-Control-Allow-Methods →GET, POST, PUT, DELETE, OPTIONS
Access-Control-Allow-Origin →*
Access-Control-Max-Age →1000
Cache-Control →no-cache, private
Connection →keep-alive
Content-Encoding →gzip
Content-Type →text/html; charset=UTF-8
Date →Mon, 30 Jan 2017 15:03:34 GMT
Server →nginx/1.10.1 (Ubuntu)
Transfer-Encoding →chunked

So what is the problem and where to dig?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Vardugin, 2017-01-31
@Aizlee

put https://github.com/barryvdh/laravel-cors
or fix your middleware:

public function handle($request, Closure $next)
{
      $response = $next($request);

      if ($response instanceof Response) {
          $response->headers->add([
              'Access-Control-Allow-Origin' => '*',
              'Access-Control-Allow-Headers' => 'authorization, allow',
              'Access-Control-Allow-Methods' => 'GET, POST, PUT, DELETE, OPTIONS'
          ]);
      }

      return $response;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question