Search code examples
node.jsexpresspostcross-domain

Disable CORS in ExpressJS


I have two nodeJS/express applications. For simplicity, I'll say one is hosted on www.example1.com and the other is hosted on www.example2.com. I want to send a POST request from www.example2.com to wwww.example1.com. I do this with the following code:

<form action="www.example1.com" method="POST">
    <input type="text" name="name"></input>
    <input type="submit" value="Submit"></input>
</form>

I only want this to accept requests from www.example1.com. How do I do this? Also, currently, when I do this post request, the POST request is actually going through. I don't understand why. Are there no default settings to prevent against the cross domain requests? How can I put up these settings.

Any help would be greatly appreciated!

Thanks!


Solution

  • the cors middleware package is the standard way to do this

    https://www.npmjs.com/package/cors

    e.g:

    const allowedOrigins = ['www.example1.com', 'www.example2.com'];
    app.use(cors({
      origin: function(origin, callback){
        if (!origin) {
          return callback(null, true);
        }
    
        if (allowedOrigins.includes(origin)) {
          const msg = 'The CORS policy for this site does not allow access from the specified Origin.';
          return callback(new Error(msg), false);
        }
        return callback(null, true);
      }
    
    }));