0

I'm having a problem with CORS, despite reading and implementing various solutions on SO.

I have an app that uses Express/NodeJS as an api and React JS as a front end. In development, the react app http://localhost:3000 is able to talk to the express backend http://localhost:9000with app.use(cors()).

Now I'm trying to use this app in production.

Both apps are kept in separate git repositories. React is deployed as a static website on aws s3 and works fine. Node JS is deployed on Elastic Bean Stalk and is in the ready state. I have a Postgres SQL database attached to the ebs instance(node app) that I'm able to connect to in pgadmin4.

Both apps are using the same base domain in route 53 myproject.com.

Both are configured to listen for https/443. I can hit both URLS https://myproject.com and https://api.myproject.com & they look like how they do in my localhost environment.

When I try to signup a user on my site I run into this error:

Access to XMLHttpRequest at 'https://api.myproject.com/users/signup/' from origin 'https://myproject.com' has been blocked by CORS policy: 
No 'Access-Control-Allow-Origin' header is present on the requested resource.

Both apps are able to "see" each other but that's about where it ends. Looking at my code, I can't figure out where the issue is taking place:

server.js

const express = require('express');
const cors = require('cors');
const logger = require('morgan');
const bodyParser = require('body-parser');
require('dotenv').config();

const PORT = process.env.PORT || 9000; // DEV
const app = express();

const corsOptions = {
  origin: 'https://myproject.com',
  optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
}

const allowCrossDomain = function (req, res, next) {
  res.header('Access-Control-Allow-Origin', 'https://myproject.com');
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
  res.header('Access-Control-Allow-Headers', 'Content-Type');
  next();
}

app.use(cors());

const { userRouter } = require('./routes/userRouter');

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(allowCrossDomain);

app.use((e, req, res, next) => {
  res.header("Access-Control-Allow-Origin", "https://myproject.com");
  res.header('Access-Control-Allow-Methods', 'DELETE, PUT, GET, POST');
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  if (e) {
    console.log(e);
    res.status(500).send(e.message);
  }
  next();
});

app.use('/users', userRouter);

app.listen(PORT, () => {
  console.log(`Express server is listening on PORT ${PORT}.`);
});// - TESTING

What I've tried: Most of these solutions came from this SO post: Why doesn't adding CORS headers to an OPTIONS route allow browsers to access my API?

Using just app.use(cors());

Using a wildcard * instead of a domain name.

White listing my domain with cors (from this blog post): https://daveceddia.com/access-control-allow-origin-cors-errors-in-react-express/

// Set up a whitelist and check against it:
var whitelist = ['https://myproject.com']
var corsOptions = {
  origin: function (origin, callback) {
    if (whitelist.indexOf(origin) !== -1) {
      callback(null, true)
    } else {
      callback(new Error('Not allowed by CORS'))
    }
  }
}

// Then pass them to cors:
app.use(cors(corsOptions));

I've also moved app.use(cors()) above my routes as suggested in another StackOverflow post.

At this point, I'm stuck so any help is appreciated so thanks in advance.

Community
  • 1
  • 1
Noble Polygon
  • 621
  • 5
  • 14
  • What versions of express and cors are you using? – Atlante Avila Dec 01 '19 at 07:00
  • What’s the HTTP status code of the response? You can use the Network pane in browser devtools to check. Is it a 4xx or 5xx error rather than a 200 OK success response? – sideshowbarker Dec 02 '19 at 00:03
  • I actually get 3 separate errors: #1 ```Failed to load resource: the server responded with a status of 404 ()```, #2 ```Failed to load resource: the server responded with a status of 504 (GATEWAY_TIMEOUT)``` & #3 ```Access to XMLHttpRequest at 'https://api.myproject.com/users/signup/' from origin 'https://myproject.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.``` – Noble Polygon Dec 02 '19 at 14:56

1 Answers1

2

Try requiring cors this way:

const cors = require('cors')({
    origin: 'https://yourdomain.com',
});

This way you can add origin and then just call app.use(cors()) at the top of the express app

const app = Express();
app.use(BodyParser.json());
app.use(cors);

this is the way I usually get things to work. Another factor you may be dealing with is if the domain hasn't fully propagated yet, this may be causing your regions for aws to not recognize the domain's dns. That's just a theory though.

Atlante Avila
  • 994
  • 8
  • 31