#CORS simply doesn't work - Express.js

1 messages · Page 1 of 1 (latest)

modest bluff
#

I have tried allowing CORS for months, and it just doesn't work, here's my server.js file (main file):

require('dotenv').config();
const express = require('express');
const cors = require('cors');
const helmet = require('helmet');
const http = require('http');
const app = express();
const server = http.createServer(app);
const PORT = Number(process.env.PORT) || 3000;

const allowedOrigins = [
  'https://dashboard.zsulesportes.com',
  'http://localhost:3000'
];

app.use(cors({
  origin: '*'
}));

app.use(express.json());
// app.use(helmet());

app.use((req, res, next) => {
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');
  res.setHeader('Content-Type', 'application/json; charset=utf-8');
  next();
});

This is what I have defined before my routes.

#

I also have created a response DTO, where I also try to allow cors for everyone:

exports.ResponseDTO = class {
    constructor(type, status, message, data=null) {
      this.type    = type
      this.status  = status
      this.message = message
      this.data    = data
    }

    sendResponse (res) {
      if (this.type == "Success") {
        res.setHeader('Access-Control-Allow-Origin', '*');
        res.setHeader('Access-Control-Allow-Headers', 'Authorization, Content-Type');
        res.setHeader('Content-Type', 'application/json; charset=utf-8');
        res.status(this.status).json({
            status: this.status,
            msg:    this.message,
            data:   this.data
        })
      } 
      else {
        res.setHeader('Access-Control-Allow-Origin', '*');
        res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');
        res.setHeader('Content-Type', 'application/json; charset=utf-8');
        res.status(this.status).json({
          status: this.status,
          msg:    this.message,
          erro:   this.message,
          data:   this.data
        }) 
      }
    }

}

The backend works just fine, but there's this nasty CORS error, basically it says there there is no 'Access-Control-Allow-Origin' header present on the requested resource (using React.js)

forest carbon
#

Usually you only need cors for production deployments when your UI and backend are on different servers
Is that what you're trying to do here?

modest bluff
wraith sedge
#

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

tidal orchid
#

I might not know the answer but why set cors headers again

sacred dome
#

This also happens. If your backend is on a www.domain.com and you enter domain.com, it would trigger a cors error instead. check this out ifthats the case.