title: Lumen: Enable CORS
body: <p>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 <em>OPTIONS - Request</em>. I read a lot of websites with information of CORS. I build middleware with the following content:</p>
  
  <pre><code>class CORSMiddleware
  {
      public function handle($request, \Closure $next)
      {
        $response = null;
        /* Preflight handle */
        if ($request-&gt;isMethod('OPTIONS')) {
           $response = new Response();
        } else {
           $response = $next($request);
        }
  
        $response-&gt;header('Access-Control-Allow-Methods', 'OPTIONS, HEAD, GET, POST, PUT, DELETE');
        $response-&gt;header('Access-Control-Allow-Headers', $request-&gt;header('Access-Control-Request-Headers'));
        $response-&gt;header('Access-Control-Allow-Origin', '*');
        return $response;
      }
  }
  </code></pre>
  
  <p>My client code:</p>
  
  <pre><code>var url = "http://localhost:8000/api/user";
  var xmlHttpRequest = new XMLHttpRequest();
  xmlHttpRequest.open('PUT', url, false);
  xmlHttpRequest.send('{"username": "ABC", "password": "ABC","email": "mail@cool.xyz" }');
  if (xmlHttpRequest.status == 200) {
    console.log(xmlHttpRequest.responseText);
  }
  </code></pre>
  
  <p>My request-information of GET request:</p>
  
  <pre><code>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
  </code></pre>
  
  <p>My response-information of a GET request:</p>
  
  <pre><code>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
  </code></pre>
  
  <p>My request-information of a PUT request:</p>
  
  <pre><code>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
  </code></pre>
  
  <p>My response information of a PUT request:</p>
  
  <pre><code>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
  </code></pre>
  
  <p>In the preflight there are no "Access-Control-Allow-*"-Headers. I don't know why; I enabled it with my lumen-cors-middleware.</p>