0
votes

I deployed an Express server to Elastic Beanstalk but I can't get it to give access to outside domains! I feel like I've tried a number of things that should have worked. Please take a look and let me know if there's anything I missed. Thanks in advance!

  1. Adding headers in express config

    var app = express();

    app.use(function (req, res, next) {

    // Website you wish to allow to connect
    res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8100');
    
    // Request methods you wish to allow
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
    
    // Request headers you wish to allow
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
    
    // Set to true if you need the website to include cookies in the requests sent
    // to the API (e.g. in case you use sessions)
    res.setHeader('Access-Control-Allow-Credentials', true);
    
    // Pass to next layer of middleware
    next();
    

    });

  2. Use npm module cors

    var app = express();

    app.use(cors());

  3. Changed the cors config on S3 <?xml version="1.0" encoding="UTF-8"?> <CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"> <CORSRule> <AllowedOrigin>*</AllowedOrigin> <AllowedMethod>GET</AllowedMethod> <AllowedMethod>POST</AllowedMethod> <AllowedMethod>PUT</AllowedMethod> <AllowedMethod>DELETE</AllowedMethod> <AllowedMethod>DELETE</AllowedMethod> <MaxAgeSeconds>3000</MaxAgeSeconds> <AllowedHeader>*</AllowedHeader> </CORSRule> </CORSConfiguration>

1

1 Answers

5
votes

Figured it out. And it's stupid

There was an error in my code, which I couldn't see because it was on EB. And I didn't check the logs on AWS. Finally, I deployed the server locally and ran both my app and the server on two different ports. Then I saw the error in the console.

For some reason, because of the error in my code, I was getting the Access Control Allow Origin error. Not sure the reason for that. But if you are getting it, and you think you've taken care of all the CORS stuff, then there might be an error in your code you're missing.

Good luck!