Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

CORS error on expressjs server with cors middleware already added

I have a frontend and express js server hosted on aws lightsail that uses ubuntu with nginx.

The server is set as a reversed proxy. Here is the config


location /api/ { 
proxy_pass http://localhost:4000/api/;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}

I’m trying to make a post request (login) from client to express but I get this

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource 
at http://localhost:4000/api/users/login. (Reason: CORS request did not succeed). Status 
code: (null).

but I have enabled cors on my server in multiple ways but with no success

const cors = require('cors');
const app = express();

const corsOption = {origin: "http://18.193.59.75:80"};

app.options("/*", function(req, res, next){ 
  res.header('Access-Control-Allow-Origin', '*'); 
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
  res.header('Access-Control-Allow-Headers', 
  'Content-Type, Authorization, Content-Length, X-Requested-With');
  res.send(200);});

//app.use(cors(corsOptions));
//app.options('*', cors(corsOptions));

>Solution :

Add the next() handler as given below and see if resolves your issue.

const cors = require('cors');
const app = express();

// const corsOption = {origin: "http://18.193.59.75:80"};

var corsOptions = function(req, res, next){ 
    res.header('Access-Control-Allow-Origin', '*'); 
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
    res.header('Access-Control-Allow-Headers', 
    'Content-Type, Authorization, Content-Length, X-Requested-With');
     next();
}

app.use(corsOptions);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading