Lumen: Enable CORS

Nis picture Nis · Dec 27, 2015 · Viewed 10.1k times · Source

I built an API with Lumen and want to access it with JavaScript and the XMLHttpRequest object. But every time my PUT, GET, POST, and DELETE requests are transformed into OPTIONS - Request. I read a lot of websites with information of CORS. I build middleware with the following content:

class CORSMiddleware
{
    public function handle($request, \Closure $next)
    {
      $response = null;
      /* Preflight handle */
      if ($request->isMethod('OPTIONS')) {
         $response = new Response();
      } else {
         $response = $next($request);
      }

      $response->header('Access-Control-Allow-Methods', 'OPTIONS, HEAD, GET, POST, PUT, DELETE');
      $response->header('Access-Control-Allow-Headers', $request->header('Access-Control-Request-Headers'));
      $response->header('Access-Control-Allow-Origin', '*');
      return $response;
    }
}

My client code:

var url = "http://localhost:8000/api/user";
var xmlHttpRequest = new XMLHttpRequest();
xmlHttpRequest.open('PUT', url, false);
xmlHttpRequest.send('{"username": "ABC", "password": "ABC","email": "[email protected]" }');
if (xmlHttpRequest.status == 200) {
  console.log(xmlHttpRequest.responseText);
}

My request-information of GET request:

Host: localhost:8000
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:43.0) Gecko/20100101 Firefox/43.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: de,en-US;q=0.7,en;q=0.3
Accept-Encoding: gzip, deflate
Origin: null
Connection: keep-alive
Cache-Control: max-age=0

My response-information of a GET request:

Access-Control-Allow-Methods: OPTIONS, HEAD, GET, POST, PUT, DELETE
Access-Control-Allow-Origin: *
Cache-Control: no-cache
Connection: close
Content-Type: text/html; charset=UTF-8
Date: Sun, 27 Dec 2015 10:36:51 GMT
Host: localhost:8000
x-powered-by: PHP/7.0.0

My request-information of a PUT request:

Host: localhost:8000
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:43.0) Gecko/20100101 Firefox/43.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: de,en-US;q=0.7,en;q=0.3
Accept-Encoding: gzip, deflate
Access-Control-Request-Method: PUT
Origin: null
Connection: keep-alive
Cache-Control: max-age=0

My response information of a PUT request:

Cache-Control: no-cache
Connection: close
Content-Type: text/html; charset=UTF-8
Date: Sun, 27 Dec 2015 10:36:51 GMT
Host: localhost:8000
x-powered-by: PHP/7.0.0

In the preflight there are no "Access-Control-Allow-*"-Headers. I don't know why; I enabled it with my lumen-cors-middleware.

Answer

Anuj Jaha picture Anuj Jaha · Mar 30, 2017

Add following headers into public/.htaccess file.

Header set Access-Control-Allow-Origin "*" 
Header set  Access-Control-Allow-Methods "GET,POST,PUT,DELETE,OPTIONS"
Header set Access-Control-Allow-Credentials "true"

this is working fine for to resolve Cross Origin Issue.