Node.js
Cors blocking access from my client application

4

Asked 2 years ago,
Active 2 years ago,
1 comment
•  375 views
nodeman asked this question 2 years ago
nodeman
2 years ago

I currently have both my client side and API being served on Heroku, but Cors is blocking access to my API. This is only happening in my production environment, as my local environments work as expected. I've tried multiple combinations of Cors policies in my API, and from each request that is sent from my client side, I am sending { withCredentials: true }. Below is the current code that I have in my app.js.


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

var app = express(); 

const options = {
  origin: 'https://myclientapp.com',
  credentials: 'true'
};

app.use(cors(options)); 

app.listen(process.env.PORT || 3000, () => {
  console.log(`Sever is listening on port: ${process.env.PORT}`);
});

Any help would be great

ProgrammingStoop commented 2 years ago
nodeman marked this answer 2 years ago
ProgrammingStoop 2 years ago

CORS errors are never fun to debug, and I certainly am not an expert when it comes to debugging these errors and finding the root cause of them but I have some things that may help.

In the past I've had issues with Heroku's proxies denying access from my client application, this can be solved by using

app.set('trust proxy', 1); 

If this does not fix the issue, then you can try a different CORS policy either with or without the "trust proxy" like the modified code below.

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

var app = express(); 

app.use(cors()); 

app.use((req, res, next) => {
  res.setHeader("Access-Control-Allow-Origin", "https://yourclientapp.com");
  res.setHeader("Accesss-Control-Allow-Credentials", true);
  res.setHeader("Access-Control-Allow-Headers", "Orgin, X-Requested-With, Content-Type, Accept, authorization");
  res.setHeader("Access-Control-Allow-Methods", "GET, POST, PATCH, PUT, DELETE, OPTIONS");
  next();

});

app.listen(process.env.PORT || 3000, () => {
  console.log(`Sever is listening on port: ${process.env.PORT}`);
});

If these don't work, feel free to send me a message...

1

1
relpy
answer
Leave a comment
Leave a comment