Search code examples
javascriptphpcorslumensuperagent

Request blocked by CORS policy using superagent and a Lumen API


I have create a REST API using PHP Lumen framework to which I removed all CORS restriction for development using:

// Enable CORS on all API routes
header('Access-Control-Allow-Origin: *');
header("Access-Control-Expose-Headers: Content-Length, X-JSON");
header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Origin, Authorization, Lang, Content-Type, X-Auth-Token');

Then on the frontend I use the library superagent to call it . For example I call the route POST http://127.0.0.1:8000/auth/register:

superagent.post('http://127.0.0.1:8000/auth/register').send({
  name: 'name',
  email: 'test@test.test',
  password: '1234Test'
}).type('application/json')
  .end((err, res) => {
    console.log(res)
    console.log(err)
  })

Sadly I get a CORS error message that I can't understand:

Access to XMLHttpRequest at 'http://127.0.0.1:8000/auth/register' from origin 'http://localhost:9000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

I make some research but I can't find anything for the error It does not have HTTP ok status and testing this same request on Postman give me no error but the normal behaviour.

Have someone an idea how I can solve it? Where I can find some documentation about this type of error?


Solution

  • I'm quite curious why you're setting the headers "manually" on your own rather than using some existing and proven CORS-Middlwares which will do all the magic for you. I would avoid reinventing the wheel unless you need it for study-cases.

    Here is a duplicate on stackoverflow:

    Enable CORS in lumen

    Here is the official documentation about lumen middlewares:

    https://lumen.laravel.com/docs/7.x/middleware

    Here are some well structured and known middlewares which will do the job for you: