How to allow CORS?












533















I am trying to support CORS in my Node.js application that uses the Express.js web framework. I have read a Google group discussion about how to handle this, and read a few articles about how CORS works. First, I did this (code is written in CoffeeScript syntax):



app.options "*", (req, res) ->
res.header 'Access-Control-Allow-Origin', '*'
res.header 'Access-Control-Allow-Credentials', true
# try: 'POST, GET, PUT, DELETE, OPTIONS'
res.header 'Access-Control-Allow-Methods', 'GET, OPTIONS'
# try: 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept'
res.header 'Access-Control-Allow-Headers', 'Content-Type'
# ...


It doesn't seem to work. It seems like my browser (Chrome) is not sending the initial OPTIONS request. When I just updated the block for the resource I need to submit a cross-origin GET request to:



app.get "/somethingelse", (req, res) ->
# ...
res.header 'Access-Control-Allow-Origin', '*'
res.header 'Access-Control-Allow-Credentials', true
res.header 'Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, OPTIONS'
res.header 'Access-Control-Allow-Headers', 'Content-Type'
# ...


It works (in Chrome). This also works in Safari.



I have read that...




In a browser implementing CORS, each cross-origin GET or POST request is preceded by an OPTIONS request that checks whether the GET or POST is OK.




So my main question is, how come this doesn't seem to happen in my case? Why isn't my app.options block called? Why do I need to set the headers in my main app.get block?










share|improve this question




















  • 1





    The golden rule of CoffeeScript is: "It's just JavaScript".

    – SSH This
    Jul 20 '16 at 17:22
















533















I am trying to support CORS in my Node.js application that uses the Express.js web framework. I have read a Google group discussion about how to handle this, and read a few articles about how CORS works. First, I did this (code is written in CoffeeScript syntax):



app.options "*", (req, res) ->
res.header 'Access-Control-Allow-Origin', '*'
res.header 'Access-Control-Allow-Credentials', true
# try: 'POST, GET, PUT, DELETE, OPTIONS'
res.header 'Access-Control-Allow-Methods', 'GET, OPTIONS'
# try: 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept'
res.header 'Access-Control-Allow-Headers', 'Content-Type'
# ...


It doesn't seem to work. It seems like my browser (Chrome) is not sending the initial OPTIONS request. When I just updated the block for the resource I need to submit a cross-origin GET request to:



app.get "/somethingelse", (req, res) ->
# ...
res.header 'Access-Control-Allow-Origin', '*'
res.header 'Access-Control-Allow-Credentials', true
res.header 'Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, OPTIONS'
res.header 'Access-Control-Allow-Headers', 'Content-Type'
# ...


It works (in Chrome). This also works in Safari.



I have read that...




In a browser implementing CORS, each cross-origin GET or POST request is preceded by an OPTIONS request that checks whether the GET or POST is OK.




So my main question is, how come this doesn't seem to happen in my case? Why isn't my app.options block called? Why do I need to set the headers in my main app.get block?










share|improve this question




















  • 1





    The golden rule of CoffeeScript is: "It's just JavaScript".

    – SSH This
    Jul 20 '16 at 17:22














533












533








533


205






I am trying to support CORS in my Node.js application that uses the Express.js web framework. I have read a Google group discussion about how to handle this, and read a few articles about how CORS works. First, I did this (code is written in CoffeeScript syntax):



app.options "*", (req, res) ->
res.header 'Access-Control-Allow-Origin', '*'
res.header 'Access-Control-Allow-Credentials', true
# try: 'POST, GET, PUT, DELETE, OPTIONS'
res.header 'Access-Control-Allow-Methods', 'GET, OPTIONS'
# try: 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept'
res.header 'Access-Control-Allow-Headers', 'Content-Type'
# ...


It doesn't seem to work. It seems like my browser (Chrome) is not sending the initial OPTIONS request. When I just updated the block for the resource I need to submit a cross-origin GET request to:



app.get "/somethingelse", (req, res) ->
# ...
res.header 'Access-Control-Allow-Origin', '*'
res.header 'Access-Control-Allow-Credentials', true
res.header 'Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, OPTIONS'
res.header 'Access-Control-Allow-Headers', 'Content-Type'
# ...


It works (in Chrome). This also works in Safari.



I have read that...




In a browser implementing CORS, each cross-origin GET or POST request is preceded by an OPTIONS request that checks whether the GET or POST is OK.




So my main question is, how come this doesn't seem to happen in my case? Why isn't my app.options block called? Why do I need to set the headers in my main app.get block?










share|improve this question
















I am trying to support CORS in my Node.js application that uses the Express.js web framework. I have read a Google group discussion about how to handle this, and read a few articles about how CORS works. First, I did this (code is written in CoffeeScript syntax):



app.options "*", (req, res) ->
res.header 'Access-Control-Allow-Origin', '*'
res.header 'Access-Control-Allow-Credentials', true
# try: 'POST, GET, PUT, DELETE, OPTIONS'
res.header 'Access-Control-Allow-Methods', 'GET, OPTIONS'
# try: 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept'
res.header 'Access-Control-Allow-Headers', 'Content-Type'
# ...


It doesn't seem to work. It seems like my browser (Chrome) is not sending the initial OPTIONS request. When I just updated the block for the resource I need to submit a cross-origin GET request to:



app.get "/somethingelse", (req, res) ->
# ...
res.header 'Access-Control-Allow-Origin', '*'
res.header 'Access-Control-Allow-Credentials', true
res.header 'Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, OPTIONS'
res.header 'Access-Control-Allow-Headers', 'Content-Type'
# ...


It works (in Chrome). This also works in Safari.



I have read that...




In a browser implementing CORS, each cross-origin GET or POST request is preceded by an OPTIONS request that checks whether the GET or POST is OK.




So my main question is, how come this doesn't seem to happen in my case? Why isn't my app.options block called? Why do I need to set the headers in my main app.get block?







node.js express coffeescript cors






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Apr 10 '17 at 8:15









Miles Rout

9501124




9501124










asked Aug 15 '11 at 16:53









mikongmikong

3,29731115




3,29731115








  • 1





    The golden rule of CoffeeScript is: "It's just JavaScript".

    – SSH This
    Jul 20 '16 at 17:22














  • 1





    The golden rule of CoffeeScript is: "It's just JavaScript".

    – SSH This
    Jul 20 '16 at 17:22








1




1





The golden rule of CoffeeScript is: "It's just JavaScript".

– SSH This
Jul 20 '16 at 17:22





The golden rule of CoffeeScript is: "It's just JavaScript".

– SSH This
Jul 20 '16 at 17:22












23 Answers
23






active

oldest

votes


















117














To answer your main question, the CORS spec only requires the OPTIONS call to precede the POST or GET if the POST or GET has any non-simple content or headers in it.



Content-Types that require a CORS pre-flight request (the OPTIONS call) are any Content-Type except the following:




  1. application/x-www-form-urlencoded

  2. multipart/form-data

  3. text/plain


Any other Content-Types apart from those listed above will trigger a pre-flight request.



As for Headers, any Request Headers apart from the following will trigger a pre-flight request:




  1. Accept

  2. Accept-Language

  3. Content-Language

  4. Content-Type

  5. DPR

  6. Save-Data

  7. Viewport-Width

  8. Width


Any other Request Headers will trigger the pre-flight request.



So, you could add a custom header such as: x-Trigger: CORS, and that should trigger the pre-flight request and hit the OPTIONS block.



See MDN Web API Reference - CORS Preflighted requests






share|improve this answer





















  • 4





    Can you provide an example?

    – Glen Pierce
    Apr 29 '18 at 17:53






  • 3





    The page I linked to seems to have a number of examples. Could you tell me what example you think is missing?

    – Dobes Vandermeer
    Apr 30 '18 at 19:26






  • 2





    In general though, link-only answers are fragile because they could, at any moment, be broken. That said, this answer seems good enough in that it's highlighting the general conditions under which OPTIONS blocks don't send. Would be nice if it had the list of accepted HEADERS, or which content-types require OPTIONS, etc but it's a good start

    – dwanderson
    Jun 19 '18 at 1:38



















584














I found the easiest way is to use the node.js package cors. The simplest usage is:



var cors = require('cors')

var app = express()
app.use(cors())


There are, of course many ways to configure the behaviour to your needs; the page linked above shows a number of examples.






share|improve this answer





















  • 1





    It fails for me when I use it with credentials. :( Everything else worked like a charm.. But its of no use to me if it fails withCredentials set to true

    – Sambhav Sharma
    Jun 27 '14 at 22:15











  • Its working fine for ajax request. I want CORS implementation for Script Tags and iFrame because in these requests the Origin is not present in the request header :( How to implement this ?

    – akashPatra
    Aug 20 '14 at 7:50






  • 33





    You need to also set cors({credentials: true, origin: true})

    – nlawson
    Nov 4 '14 at 15:49











  • how do you enable options preflight here?

    – chovy
    Dec 19 '18 at 6:55











  • @nlawson ahh You saved me

    – adam west
    Dec 23 '18 at 15:24



















414














Try passing control to the next matching route. If Express is matching app.get route first, then it won't continue onto the options route unless you do this (note use of next):



app.get('somethingelse', function(req, res, next) {
//..set headers etc.

next();
});


In terms of organising the CORS stuff, I put it in a middleware which is working well for me:



//CORS middleware
var allowCrossDomain = function(req, res, next) {
res.header('Access-Control-Allow-Origin', 'example.com');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type');

next();
}

//...
app.configure(function() {
app.use(express.bodyParser());
app.use(express.cookieParser());
app.use(express.session({ secret: 'cool beans' }));
app.use(express.methodOverride());
app.use(allowCrossDomain);
app.use(app.router);
app.use(express.static(__dirname + '/public'));
});





share|improve this answer





















  • 1





    I believe OPTIONS happens before a GET, whereas if you're doing a POST - there is no OPTIONS request...

    – Nick
    Sep 13 '11 at 15:14






  • 14





    I use app.options("*", function(req,res,next){....res.send(200)...

    – fullstacklife
    May 31 '12 at 3:26






  • 21





    Is config.allowedDomains a comma-delimited string or an array?

    – pixelfreak
    Nov 17 '12 at 2:56






  • 2





    config.allowedDomains should be a space separated array

    – mcfedr
    Mar 20 '13 at 8:10






  • 1





    The extra session was removed by simply rearranging the express middleware order. On another note, this needs a little more security. if the origin is not in the allowed domain then the request is still processed, only the browser won't be able to see it plus the origin can be spoofed. My advice would be to do a check and if the origin is not in the allowed list then return 403 immediately. Also is any sensitive information is being served, validate the user via a session.

    – Xerri
    Sep 19 '13 at 10:52



















109














To stay in the same idea of routing. I use this code :



app.all('/*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
next();
});


Similar to http://enable-cors.org/server_expressjs.html example






share|improve this answer





















  • 1





    This goes in the grunt.js file?

    – Oliver Dixon
    Jan 2 '15 at 2:13






  • 4





    What about preflight?

    – backdesk
    Feb 4 '15 at 13:01



















60














do



npm install cors --save


and just add these lines in your main file where your request going (keep it before any route).



const cors = require('cors');
const express = require('express');
let app = express();
app.use(cors());
app.options('*', cors());





share|improve this answer





















  • 1





    app.options('*', cors()) // include before other routes

    – Rajeshwar
    Nov 12 '18 at 10:47



















48














I have made a more complete middleware suitable for express or connect. It supports OPTIONS requests for preflight checking. Note that it will allow CORS access to anything, you might want to put in some checks if you want to limit access.



app.use(function(req, res, next) {
var oneof = false;
if(req.headers.origin) {
res.header('Access-Control-Allow-Origin', req.headers.origin);
oneof = true;
}
if(req.headers['access-control-request-method']) {
res.header('Access-Control-Allow-Methods', req.headers['access-control-request-method']);
oneof = true;
}
if(req.headers['access-control-request-headers']) {
res.header('Access-Control-Allow-Headers', req.headers['access-control-request-headers']);
oneof = true;
}
if(oneof) {
res.header('Access-Control-Max-Age', 60 * 60 * 24 * 365);
}

// intercept OPTIONS method
if (oneof && req.method == 'OPTIONS') {
res.send(200);
}
else {
next();
}
});





share|improve this answer


























  • Hey there, I came across your solution and was wondering if the 'oneof' flag should be set false if one of the headers wasn't detected?

    – Leonidas
    Mar 19 '13 at 21:14






  • 1





    Some requests will not have all the headers. Specifically a GET request will be sent by the browser, and when it doesn't get a correct allow-origin response an error is given to js. Whereas for a POST request, the OPTIONS request is first sent, with the allow-method header, and only afterwards, the actual POST request will be sent.

    – mcfedr
    Mar 20 '13 at 8:06








  • 1





    Ah, I see. Thanks. Did you ever run into trouble by not putting res.send(200) in there if the req method was 'options'?

    – Leonidas
    Mar 20 '13 at 14:24













  • I dont think i have tried sending something else, I would imagine any other response will cause the browser to refuse the request that it is preflighting.

    – mcfedr
    Mar 20 '13 at 15:19






  • 1





    omg I love you @mcfedr - a +1 doesn't capture it!

    – ErichBSchulz
    Mar 12 '18 at 12:56



















33














install cors module of expressjs. you can follow these steps >



Installation



npm install cors


Simple Usage (Enable All CORS Requests)



var express = require('express');
var cors = require('cors');
var app = express();
app.use(cors());


for more details go to https://github.com/expressjs/cors






share|improve this answer



















  • 2





    TypeError: Cannot read property 'headers' of undefined The most basic app setup.

    – Oliver Dixon
    Dec 3 '17 at 19:51













  • Are you sure you have request object ? :)

    – codebased
    Apr 12 '18 at 23:25



















29














Do something like this:



app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});





share|improve this answer



















  • 3





    this is the solution on enable-cors.org/server_expressjs.html

    – Z. Khullah
    Nov 12 '16 at 19:38



















19














Testing done with express + node + ionic running in differente ports.



Localhost:8100



Localhost:5000



// CORS (Cross-Origin Resource Sharing) headers to support Cross-site HTTP requests

app.all('*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.header('Access-Control-Allow-Headers', 'Content-Type');
next();
});





share|improve this answer





















  • 2





    In which file do we need to add this lines?

    – Shefalee Chaudhary
    Dec 15 '16 at 10:24



















19














first simply install cors in your project.
Take terminal(command prompt) and cd to your project directory and run the below command:



npm install cors --save


Then take the server.js file and change the code to add the following in it:



var cors = require('cors');


var app = express();

app.use(cors());

app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header('Access-Control-Allow-Methods', 'DELETE, PUT, GET, POST');
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});


This worked for me..






share|improve this answer





















  • 2





    You don't need cors if you're doing the res.header stuff. cors is a library that handles all that for you. Delete your first & 3rd lines (AKA everything with cors) and you'll find that it still works.

    – thisissami
    Sep 7 '17 at 19:25











  • heck i'm pretty sure all you really need is this line res.header("Access-Control-Allow-Origin", "*");

    – thisissami
    Sep 7 '17 at 19:26











  • though do keep in mind that you're compromising your security by doing that. :)

    – thisissami
    Sep 7 '17 at 19:27



















10














This works for me, as its an easy implementation inside the routes, im using meanjs and its working fine, safari, chrome, etc.



app.route('/footer-contact-form').post(emailer.sendFooterMail).options(function(req,res,next){ 
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET, POST');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
return res.send(200);

});





share|improve this answer































    9














    Some time ago, I faced this problem so I did this to allow CORS in my nodejs app:



    First you need to install cors by using below command :



    npm install cors --save


    Now add the following code to your app starting file like ( app.js or server.js)



    var express = require('express');
    var app = express();

    var cors = require('cors');
    var bodyParser = require('body-parser');

    //enables cors
    app.use(cors({
    'allowedHeaders': ['sessionId', 'Content-Type'],
    'exposedHeaders': ['sessionId'],
    'origin': '*',
    'methods': 'GET,HEAD,PUT,PATCH,POST,DELETE',
    'preflightContinue': false
    }));

    require('./router/index')(app);





    share|improve this answer


























    • This is the only part of code from my app.js.

      – Shubham Verma
      Jan 24 '17 at 10:20











    • tried this after installing cors. Cors is not a function

      – colin rickels
      Jul 6 '18 at 13:27



















    7














    If you want to make it controller specific, you can use:



    res.setHeader('X-Frame-Options', 'ALLOWALL');
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'POST, GET');
    res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');


    Please note that this will also allow iframes.






    share|improve this answer































      4














      Can refer the code below for the same. Source: Academind/node-restful-api



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

      //acts as a middleware
      //to handle CORS Errors
      app.use((req, res, next) => { //doesn't send response just adjusts it
      res.header("Access-Control-Allow-Origin", "*") //* to give access to any origin
      res.header(
      "Access-Control-Allow-Headers",
      "Origin, X-Requested-With, Content-Type, Accept, Authorization" //to give access to all the headers provided
      );
      if(req.method === 'OPTIONS'){
      res.header('Access-Control-Allow-Methods', 'PUT, POST, PATCH, DELETE, GET'); //to give access to all the methods provided
      return res.status(200).json({});
      }
      next(); //so that other routes can take over
      })





      share|improve this answer
























      • I saw many answer and this have something which is importan, I tried to use this part of the code after some other configurations and it didn't work and for some reason, I tried putting the code after app const app = express(); and works! I think is important to mention it.

        – rfcabal
        Jan 13 at 0:45



















      3














      My simplest solution with Express 4.2.0 (EDIT: Doesn't seem to work in 4.3.0) was:



      function supportCrossOriginScript(req, res, next) {
      res.status(200);
      res.header("Access-Control-Allow-Origin", "*");
      res.header("Access-Control-Allow-Headers", "Content-Type");

      // res.header("Access-Control-Allow-Headers", "Origin");
      // res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
      // res.header("Access-Control-Allow-Methods","POST, OPTIONS");
      // res.header("Access-Control-Allow-Methods","POST, GET, OPTIONS, DELETE, PUT, HEAD");
      // res.header("Access-Control-Max-Age","1728000");
      next();
      }

      // Support CORS
      app.options('/result', supportCrossOriginScript);

      app.post('/result', supportCrossOriginScript, function(req, res) {
      res.send('received');
      // do stuff with req
      });


      I suppose doing app.all('/result', ...) would work too...






      share|improve this answer

































        3














        In addition to what others have said, don't forget that unless using nodemon you will need to restart your node server for the changes to take effect!



        I personally had been refreshing my browser out of habit, forgetting that it's server side code.






        share|improve this answer































          2














          I found it to be extremely easy to do this with the npm request package (https://www.npmjs.com/package/request)



          Then I based my solution on this post http://blog.javascripting.com/2015/01/17/dont-hassle-with-cors/



          'use strict'

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

          let proxyConfig = {
          url : {
          base: 'http://servertoreach.com?id=',
          }
          }

          /* setting up and configuring node express server for the application */
          let server = express();
          server.set('port', 3000);


          /* methods forwarded to the servertoreach proxy */
          server.use('/somethingElse', function(req, res)
          {
          let url = proxyConfig.url.base + req.query.id;
          req.pipe(request(url)).pipe(res);
          });


          /* start the server */
          server.listen(server.get('port'), function() {
          console.log('express server with a proxy listening on port ' + server.get('port'));
          });





          share|improve this answer































            2














            Using Express Middleware works great for me. If you are already using Express, just add the following middleware rules. It should start working.



            app.all("/api/*", function(req, res, next) {
            res.header("Access-Control-Allow-Origin", "*");
            res.header("Access-Control-Allow-Headers", "Cache-Control, Pragma, Origin, Authorization, Content-Type, X-Requested-With");
            res.header("Access-Control-Allow-Methods", "GET, PUT, POST");
            return next();
            });

            app.all("/api/*", function(req, res, next) {
            if (req.method.toLowerCase() !== "options") {
            return next();
            }
            return res.send(204);
            });


            Reference






            share|improve this answer































              1














              We can avoid CORS and forward the requests to the other server instead:



              // config:
              var public_folder = __dirname + '/public'
              var apiServerHost = 'http://other.server'

              // code:
              console.log("starting server...");

              var express = require('express');
              var app = express();
              var request = require('request');

              // serve static files
              app.use(express.static(public_folder));

              // if not found, serve from another server
              app.use(function(req, res) {
              var url = apiServerHost + req.url;
              req.pipe(request(url)).pipe(res);
              });

              app.listen(80, function(){
              console.log("server ready");
              });





              share|improve this answer


























              • this does not answer the question asked

                – david.barkhuizen
                Jan 16 '18 at 12:53



















              1














              I used the following steps to my web app and I had success:



              Add the cors package to the express:



              npm install cors --save


              Add following lines after the bodyParser configuration. I had some troubles adding before bodyParser:



               // enable cors to the server
              const corsOpt = {
              origin: process.env.CORS_ALLOW_ORIGIN || '*', // this work well to configure origin url in the server
              methods: ['GET', 'PUT', 'POST', 'DELETE', 'OPTIONS'], // to works well with web app, OPTIONS is required
              allowedHeaders: ['Content-Type', 'Authorization'] // allow json and token in the headers
              };
              app.use(cors(corsOpt)); // cors for all the routes of the application
              app.options('*', cors(corsOpt)); // automatic cors gen for HTTP verbs in all routes, This can be redundant but I kept to be sure that will always work.





              share|improve this answer































                0














                This is similiar to Pat's answer with the difference that I finish with res.sendStatus(200); instead of next();



                The code will catch all the requests of the method type OPTIONS and send back access-control-headers.



                app.options('/*', (req, res, next) => {
                res.header('Access-Control-Allow-Origin', '*');
                res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
                res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');
                res.sendStatus(200);
                });


                The code accepts CORS from all origins as requested in the question. However, it would be better to replace the * with a specific origin i.e. http://localhost:8080 to prevent misuse.



                Since we use the app.options-method instead of the app.use-method we don't need to make this check:



                req.method === 'OPTIONS'


                which we can see in some of the other answers.



                I found the answer here: http://johnzhang.io/options-request-in-express.






                share|improve this answer

































                  -1














                  In typescript, if you want to use the node.js package cors



                  /**
                  * app.ts
                  * If you use the cors library
                  */

                  import * as express from "express";
                  [...]
                  import * as cors from 'cors';

                  class App {
                  public express: express.Application;

                  constructor() {
                  this.express = express();
                  [..]
                  this.handleCORSErrors();
                  }

                  private handleCORSErrors(): any {
                  const corsOptions: cors.CorsOptions = {
                  origin: 'http://example.com',
                  optionsSuccessStatus: 200
                  };
                  this.express.use(cors(corsOptions));
                  }
                  }

                  export default new App().express;


                  If you don't want to use third part libraries for cors error handling, you need to change the handleCORSErrors() method.



                  /**
                  * app.ts
                  * If you do not use the cors library
                  */

                  import * as express from "express";
                  [...]

                  class App {
                  public express: express.Application;

                  constructor() {
                  this.express = express();
                  [..]
                  this.handleCORSErrors();
                  }

                  private handleCORSErrors(): any {
                  this.express.use((req, res, next) => {
                  res.header("Access-Control-Allow-Origin", "*");
                  res.header(
                  "Access-Control-ALlow-Headers",
                  "Origin, X-Requested-With, Content-Type, Accept, Authorization"
                  );
                  if (req.method === "OPTIONS") {
                  res.header(
                  "Access-Control-Allow-Methods",
                  "PUT, POST, PATCH, GET, DELETE"
                  );
                  return res.status(200).json({});
                  }
                  next(); // send the request to the next middleware
                  });
                  }
                  }

                  export default new App().express;


                  For using the app.ts file



                  /**
                  * server.ts
                  */
                  import * as http from "http";
                  import app from "./app";

                  const server: http.Server = http.createServer(app);

                  const PORT: any = process.env.PORT || 3000;
                  server.listen(PORT);





                  share|improve this answer





















                  • 1





                    "If the server is written in typescript" — It isn't. The question says it is written in CoffeeScript.

                    – Quentin
                    Jul 9 '18 at 9:44






                  • 1





                    @Quentin I just wanted to show an alternative in typesript, hoping that this could help somebody.

                    – overcomer
                    Jul 9 '18 at 9:49



















                  -1














                  Below code will work ,but first install cors by:



                  npm install --save cors



                  Then:



                  module.exports = function(app) { 
                  var express = require("express");
                  var cors = require('cors');
                  var router = express.Router();
                  app.use(cors());

                  app.post("/movies",cors(), function(req, res) {
                  res.send("test");
                  });





                  share|improve this answer





















                  • 2





                    Duplicate answer. There are already answers like this here.

                    – Maihan Nijat
                    Oct 17 '18 at 16:03










                  protected by Community Oct 27 '17 at 8:04



                  Thank you for your interest in this question.
                  Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).



                  Would you like to answer one of these unanswered questions instead?














                  23 Answers
                  23






                  active

                  oldest

                  votes








                  23 Answers
                  23






                  active

                  oldest

                  votes









                  active

                  oldest

                  votes






                  active

                  oldest

                  votes









                  117














                  To answer your main question, the CORS spec only requires the OPTIONS call to precede the POST or GET if the POST or GET has any non-simple content or headers in it.



                  Content-Types that require a CORS pre-flight request (the OPTIONS call) are any Content-Type except the following:




                  1. application/x-www-form-urlencoded

                  2. multipart/form-data

                  3. text/plain


                  Any other Content-Types apart from those listed above will trigger a pre-flight request.



                  As for Headers, any Request Headers apart from the following will trigger a pre-flight request:




                  1. Accept

                  2. Accept-Language

                  3. Content-Language

                  4. Content-Type

                  5. DPR

                  6. Save-Data

                  7. Viewport-Width

                  8. Width


                  Any other Request Headers will trigger the pre-flight request.



                  So, you could add a custom header such as: x-Trigger: CORS, and that should trigger the pre-flight request and hit the OPTIONS block.



                  See MDN Web API Reference - CORS Preflighted requests






                  share|improve this answer





















                  • 4





                    Can you provide an example?

                    – Glen Pierce
                    Apr 29 '18 at 17:53






                  • 3





                    The page I linked to seems to have a number of examples. Could you tell me what example you think is missing?

                    – Dobes Vandermeer
                    Apr 30 '18 at 19:26






                  • 2





                    In general though, link-only answers are fragile because they could, at any moment, be broken. That said, this answer seems good enough in that it's highlighting the general conditions under which OPTIONS blocks don't send. Would be nice if it had the list of accepted HEADERS, or which content-types require OPTIONS, etc but it's a good start

                    – dwanderson
                    Jun 19 '18 at 1:38
















                  117














                  To answer your main question, the CORS spec only requires the OPTIONS call to precede the POST or GET if the POST or GET has any non-simple content or headers in it.



                  Content-Types that require a CORS pre-flight request (the OPTIONS call) are any Content-Type except the following:




                  1. application/x-www-form-urlencoded

                  2. multipart/form-data

                  3. text/plain


                  Any other Content-Types apart from those listed above will trigger a pre-flight request.



                  As for Headers, any Request Headers apart from the following will trigger a pre-flight request:




                  1. Accept

                  2. Accept-Language

                  3. Content-Language

                  4. Content-Type

                  5. DPR

                  6. Save-Data

                  7. Viewport-Width

                  8. Width


                  Any other Request Headers will trigger the pre-flight request.



                  So, you could add a custom header such as: x-Trigger: CORS, and that should trigger the pre-flight request and hit the OPTIONS block.



                  See MDN Web API Reference - CORS Preflighted requests






                  share|improve this answer





















                  • 4





                    Can you provide an example?

                    – Glen Pierce
                    Apr 29 '18 at 17:53






                  • 3





                    The page I linked to seems to have a number of examples. Could you tell me what example you think is missing?

                    – Dobes Vandermeer
                    Apr 30 '18 at 19:26






                  • 2





                    In general though, link-only answers are fragile because they could, at any moment, be broken. That said, this answer seems good enough in that it's highlighting the general conditions under which OPTIONS blocks don't send. Would be nice if it had the list of accepted HEADERS, or which content-types require OPTIONS, etc but it's a good start

                    – dwanderson
                    Jun 19 '18 at 1:38














                  117












                  117








                  117







                  To answer your main question, the CORS spec only requires the OPTIONS call to precede the POST or GET if the POST or GET has any non-simple content or headers in it.



                  Content-Types that require a CORS pre-flight request (the OPTIONS call) are any Content-Type except the following:




                  1. application/x-www-form-urlencoded

                  2. multipart/form-data

                  3. text/plain


                  Any other Content-Types apart from those listed above will trigger a pre-flight request.



                  As for Headers, any Request Headers apart from the following will trigger a pre-flight request:




                  1. Accept

                  2. Accept-Language

                  3. Content-Language

                  4. Content-Type

                  5. DPR

                  6. Save-Data

                  7. Viewport-Width

                  8. Width


                  Any other Request Headers will trigger the pre-flight request.



                  So, you could add a custom header such as: x-Trigger: CORS, and that should trigger the pre-flight request and hit the OPTIONS block.



                  See MDN Web API Reference - CORS Preflighted requests






                  share|improve this answer















                  To answer your main question, the CORS spec only requires the OPTIONS call to precede the POST or GET if the POST or GET has any non-simple content or headers in it.



                  Content-Types that require a CORS pre-flight request (the OPTIONS call) are any Content-Type except the following:




                  1. application/x-www-form-urlencoded

                  2. multipart/form-data

                  3. text/plain


                  Any other Content-Types apart from those listed above will trigger a pre-flight request.



                  As for Headers, any Request Headers apart from the following will trigger a pre-flight request:




                  1. Accept

                  2. Accept-Language

                  3. Content-Language

                  4. Content-Type

                  5. DPR

                  6. Save-Data

                  7. Viewport-Width

                  8. Width


                  Any other Request Headers will trigger the pre-flight request.



                  So, you could add a custom header such as: x-Trigger: CORS, and that should trigger the pre-flight request and hit the OPTIONS block.



                  See MDN Web API Reference - CORS Preflighted requests







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Sep 24 '18 at 8:33









                  Craig

                  605




                  605










                  answered Dec 20 '11 at 8:32









                  Dobes VandermeerDobes Vandermeer

                  5,30233137




                  5,30233137








                  • 4





                    Can you provide an example?

                    – Glen Pierce
                    Apr 29 '18 at 17:53






                  • 3





                    The page I linked to seems to have a number of examples. Could you tell me what example you think is missing?

                    – Dobes Vandermeer
                    Apr 30 '18 at 19:26






                  • 2





                    In general though, link-only answers are fragile because they could, at any moment, be broken. That said, this answer seems good enough in that it's highlighting the general conditions under which OPTIONS blocks don't send. Would be nice if it had the list of accepted HEADERS, or which content-types require OPTIONS, etc but it's a good start

                    – dwanderson
                    Jun 19 '18 at 1:38














                  • 4





                    Can you provide an example?

                    – Glen Pierce
                    Apr 29 '18 at 17:53






                  • 3





                    The page I linked to seems to have a number of examples. Could you tell me what example you think is missing?

                    – Dobes Vandermeer
                    Apr 30 '18 at 19:26






                  • 2





                    In general though, link-only answers are fragile because they could, at any moment, be broken. That said, this answer seems good enough in that it's highlighting the general conditions under which OPTIONS blocks don't send. Would be nice if it had the list of accepted HEADERS, or which content-types require OPTIONS, etc but it's a good start

                    – dwanderson
                    Jun 19 '18 at 1:38








                  4




                  4





                  Can you provide an example?

                  – Glen Pierce
                  Apr 29 '18 at 17:53





                  Can you provide an example?

                  – Glen Pierce
                  Apr 29 '18 at 17:53




                  3




                  3





                  The page I linked to seems to have a number of examples. Could you tell me what example you think is missing?

                  – Dobes Vandermeer
                  Apr 30 '18 at 19:26





                  The page I linked to seems to have a number of examples. Could you tell me what example you think is missing?

                  – Dobes Vandermeer
                  Apr 30 '18 at 19:26




                  2




                  2





                  In general though, link-only answers are fragile because they could, at any moment, be broken. That said, this answer seems good enough in that it's highlighting the general conditions under which OPTIONS blocks don't send. Would be nice if it had the list of accepted HEADERS, or which content-types require OPTIONS, etc but it's a good start

                  – dwanderson
                  Jun 19 '18 at 1:38





                  In general though, link-only answers are fragile because they could, at any moment, be broken. That said, this answer seems good enough in that it's highlighting the general conditions under which OPTIONS blocks don't send. Would be nice if it had the list of accepted HEADERS, or which content-types require OPTIONS, etc but it's a good start

                  – dwanderson
                  Jun 19 '18 at 1:38













                  584














                  I found the easiest way is to use the node.js package cors. The simplest usage is:



                  var cors = require('cors')

                  var app = express()
                  app.use(cors())


                  There are, of course many ways to configure the behaviour to your needs; the page linked above shows a number of examples.






                  share|improve this answer





















                  • 1





                    It fails for me when I use it with credentials. :( Everything else worked like a charm.. But its of no use to me if it fails withCredentials set to true

                    – Sambhav Sharma
                    Jun 27 '14 at 22:15











                  • Its working fine for ajax request. I want CORS implementation for Script Tags and iFrame because in these requests the Origin is not present in the request header :( How to implement this ?

                    – akashPatra
                    Aug 20 '14 at 7:50






                  • 33





                    You need to also set cors({credentials: true, origin: true})

                    – nlawson
                    Nov 4 '14 at 15:49











                  • how do you enable options preflight here?

                    – chovy
                    Dec 19 '18 at 6:55











                  • @nlawson ahh You saved me

                    – adam west
                    Dec 23 '18 at 15:24
















                  584














                  I found the easiest way is to use the node.js package cors. The simplest usage is:



                  var cors = require('cors')

                  var app = express()
                  app.use(cors())


                  There are, of course many ways to configure the behaviour to your needs; the page linked above shows a number of examples.






                  share|improve this answer





















                  • 1





                    It fails for me when I use it with credentials. :( Everything else worked like a charm.. But its of no use to me if it fails withCredentials set to true

                    – Sambhav Sharma
                    Jun 27 '14 at 22:15











                  • Its working fine for ajax request. I want CORS implementation for Script Tags and iFrame because in these requests the Origin is not present in the request header :( How to implement this ?

                    – akashPatra
                    Aug 20 '14 at 7:50






                  • 33





                    You need to also set cors({credentials: true, origin: true})

                    – nlawson
                    Nov 4 '14 at 15:49











                  • how do you enable options preflight here?

                    – chovy
                    Dec 19 '18 at 6:55











                  • @nlawson ahh You saved me

                    – adam west
                    Dec 23 '18 at 15:24














                  584












                  584








                  584







                  I found the easiest way is to use the node.js package cors. The simplest usage is:



                  var cors = require('cors')

                  var app = express()
                  app.use(cors())


                  There are, of course many ways to configure the behaviour to your needs; the page linked above shows a number of examples.






                  share|improve this answer















                  I found the easiest way is to use the node.js package cors. The simplest usage is:



                  var cors = require('cors')

                  var app = express()
                  app.use(cors())


                  There are, of course many ways to configure the behaviour to your needs; the page linked above shows a number of examples.







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Aug 2 '14 at 12:02









                  Arnout Engelen

                  4,68811729




                  4,68811729










                  answered Feb 7 '14 at 8:16









                  Wayne MaurerWayne Maurer

                  8,69332336




                  8,69332336








                  • 1





                    It fails for me when I use it with credentials. :( Everything else worked like a charm.. But its of no use to me if it fails withCredentials set to true

                    – Sambhav Sharma
                    Jun 27 '14 at 22:15











                  • Its working fine for ajax request. I want CORS implementation for Script Tags and iFrame because in these requests the Origin is not present in the request header :( How to implement this ?

                    – akashPatra
                    Aug 20 '14 at 7:50






                  • 33





                    You need to also set cors({credentials: true, origin: true})

                    – nlawson
                    Nov 4 '14 at 15:49











                  • how do you enable options preflight here?

                    – chovy
                    Dec 19 '18 at 6:55











                  • @nlawson ahh You saved me

                    – adam west
                    Dec 23 '18 at 15:24














                  • 1





                    It fails for me when I use it with credentials. :( Everything else worked like a charm.. But its of no use to me if it fails withCredentials set to true

                    – Sambhav Sharma
                    Jun 27 '14 at 22:15











                  • Its working fine for ajax request. I want CORS implementation for Script Tags and iFrame because in these requests the Origin is not present in the request header :( How to implement this ?

                    – akashPatra
                    Aug 20 '14 at 7:50






                  • 33





                    You need to also set cors({credentials: true, origin: true})

                    – nlawson
                    Nov 4 '14 at 15:49











                  • how do you enable options preflight here?

                    – chovy
                    Dec 19 '18 at 6:55











                  • @nlawson ahh You saved me

                    – adam west
                    Dec 23 '18 at 15:24








                  1




                  1





                  It fails for me when I use it with credentials. :( Everything else worked like a charm.. But its of no use to me if it fails withCredentials set to true

                  – Sambhav Sharma
                  Jun 27 '14 at 22:15





                  It fails for me when I use it with credentials. :( Everything else worked like a charm.. But its of no use to me if it fails withCredentials set to true

                  – Sambhav Sharma
                  Jun 27 '14 at 22:15













                  Its working fine for ajax request. I want CORS implementation for Script Tags and iFrame because in these requests the Origin is not present in the request header :( How to implement this ?

                  – akashPatra
                  Aug 20 '14 at 7:50





                  Its working fine for ajax request. I want CORS implementation for Script Tags and iFrame because in these requests the Origin is not present in the request header :( How to implement this ?

                  – akashPatra
                  Aug 20 '14 at 7:50




                  33




                  33





                  You need to also set cors({credentials: true, origin: true})

                  – nlawson
                  Nov 4 '14 at 15:49





                  You need to also set cors({credentials: true, origin: true})

                  – nlawson
                  Nov 4 '14 at 15:49













                  how do you enable options preflight here?

                  – chovy
                  Dec 19 '18 at 6:55





                  how do you enable options preflight here?

                  – chovy
                  Dec 19 '18 at 6:55













                  @nlawson ahh You saved me

                  – adam west
                  Dec 23 '18 at 15:24





                  @nlawson ahh You saved me

                  – adam west
                  Dec 23 '18 at 15:24











                  414














                  Try passing control to the next matching route. If Express is matching app.get route first, then it won't continue onto the options route unless you do this (note use of next):



                  app.get('somethingelse', function(req, res, next) {
                  //..set headers etc.

                  next();
                  });


                  In terms of organising the CORS stuff, I put it in a middleware which is working well for me:



                  //CORS middleware
                  var allowCrossDomain = function(req, res, next) {
                  res.header('Access-Control-Allow-Origin', 'example.com');
                  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
                  res.header('Access-Control-Allow-Headers', 'Content-Type');

                  next();
                  }

                  //...
                  app.configure(function() {
                  app.use(express.bodyParser());
                  app.use(express.cookieParser());
                  app.use(express.session({ secret: 'cool beans' }));
                  app.use(express.methodOverride());
                  app.use(allowCrossDomain);
                  app.use(app.router);
                  app.use(express.static(__dirname + '/public'));
                  });





                  share|improve this answer





















                  • 1





                    I believe OPTIONS happens before a GET, whereas if you're doing a POST - there is no OPTIONS request...

                    – Nick
                    Sep 13 '11 at 15:14






                  • 14





                    I use app.options("*", function(req,res,next){....res.send(200)...

                    – fullstacklife
                    May 31 '12 at 3:26






                  • 21





                    Is config.allowedDomains a comma-delimited string or an array?

                    – pixelfreak
                    Nov 17 '12 at 2:56






                  • 2





                    config.allowedDomains should be a space separated array

                    – mcfedr
                    Mar 20 '13 at 8:10






                  • 1





                    The extra session was removed by simply rearranging the express middleware order. On another note, this needs a little more security. if the origin is not in the allowed domain then the request is still processed, only the browser won't be able to see it plus the origin can be spoofed. My advice would be to do a check and if the origin is not in the allowed list then return 403 immediately. Also is any sensitive information is being served, validate the user via a session.

                    – Xerri
                    Sep 19 '13 at 10:52
















                  414














                  Try passing control to the next matching route. If Express is matching app.get route first, then it won't continue onto the options route unless you do this (note use of next):



                  app.get('somethingelse', function(req, res, next) {
                  //..set headers etc.

                  next();
                  });


                  In terms of organising the CORS stuff, I put it in a middleware which is working well for me:



                  //CORS middleware
                  var allowCrossDomain = function(req, res, next) {
                  res.header('Access-Control-Allow-Origin', 'example.com');
                  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
                  res.header('Access-Control-Allow-Headers', 'Content-Type');

                  next();
                  }

                  //...
                  app.configure(function() {
                  app.use(express.bodyParser());
                  app.use(express.cookieParser());
                  app.use(express.session({ secret: 'cool beans' }));
                  app.use(express.methodOverride());
                  app.use(allowCrossDomain);
                  app.use(app.router);
                  app.use(express.static(__dirname + '/public'));
                  });





                  share|improve this answer





















                  • 1





                    I believe OPTIONS happens before a GET, whereas if you're doing a POST - there is no OPTIONS request...

                    – Nick
                    Sep 13 '11 at 15:14






                  • 14





                    I use app.options("*", function(req,res,next){....res.send(200)...

                    – fullstacklife
                    May 31 '12 at 3:26






                  • 21





                    Is config.allowedDomains a comma-delimited string or an array?

                    – pixelfreak
                    Nov 17 '12 at 2:56






                  • 2





                    config.allowedDomains should be a space separated array

                    – mcfedr
                    Mar 20 '13 at 8:10






                  • 1





                    The extra session was removed by simply rearranging the express middleware order. On another note, this needs a little more security. if the origin is not in the allowed domain then the request is still processed, only the browser won't be able to see it plus the origin can be spoofed. My advice would be to do a check and if the origin is not in the allowed list then return 403 immediately. Also is any sensitive information is being served, validate the user via a session.

                    – Xerri
                    Sep 19 '13 at 10:52














                  414












                  414








                  414







                  Try passing control to the next matching route. If Express is matching app.get route first, then it won't continue onto the options route unless you do this (note use of next):



                  app.get('somethingelse', function(req, res, next) {
                  //..set headers etc.

                  next();
                  });


                  In terms of organising the CORS stuff, I put it in a middleware which is working well for me:



                  //CORS middleware
                  var allowCrossDomain = function(req, res, next) {
                  res.header('Access-Control-Allow-Origin', 'example.com');
                  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
                  res.header('Access-Control-Allow-Headers', 'Content-Type');

                  next();
                  }

                  //...
                  app.configure(function() {
                  app.use(express.bodyParser());
                  app.use(express.cookieParser());
                  app.use(express.session({ secret: 'cool beans' }));
                  app.use(express.methodOverride());
                  app.use(allowCrossDomain);
                  app.use(app.router);
                  app.use(express.static(__dirname + '/public'));
                  });





                  share|improve this answer















                  Try passing control to the next matching route. If Express is matching app.get route first, then it won't continue onto the options route unless you do this (note use of next):



                  app.get('somethingelse', function(req, res, next) {
                  //..set headers etc.

                  next();
                  });


                  In terms of organising the CORS stuff, I put it in a middleware which is working well for me:



                  //CORS middleware
                  var allowCrossDomain = function(req, res, next) {
                  res.header('Access-Control-Allow-Origin', 'example.com');
                  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
                  res.header('Access-Control-Allow-Headers', 'Content-Type');

                  next();
                  }

                  //...
                  app.configure(function() {
                  app.use(express.bodyParser());
                  app.use(express.cookieParser());
                  app.use(express.session({ secret: 'cool beans' }));
                  app.use(express.methodOverride());
                  app.use(allowCrossDomain);
                  app.use(app.router);
                  app.use(express.static(__dirname + '/public'));
                  });






                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Aug 29 '14 at 14:39









                  mb21

                  18.6k36289




                  18.6k36289










                  answered Aug 15 '11 at 19:45









                  evilceleryevilcelery

                  13.1k83452




                  13.1k83452








                  • 1





                    I believe OPTIONS happens before a GET, whereas if you're doing a POST - there is no OPTIONS request...

                    – Nick
                    Sep 13 '11 at 15:14






                  • 14





                    I use app.options("*", function(req,res,next){....res.send(200)...

                    – fullstacklife
                    May 31 '12 at 3:26






                  • 21





                    Is config.allowedDomains a comma-delimited string or an array?

                    – pixelfreak
                    Nov 17 '12 at 2:56






                  • 2





                    config.allowedDomains should be a space separated array

                    – mcfedr
                    Mar 20 '13 at 8:10






                  • 1





                    The extra session was removed by simply rearranging the express middleware order. On another note, this needs a little more security. if the origin is not in the allowed domain then the request is still processed, only the browser won't be able to see it plus the origin can be spoofed. My advice would be to do a check and if the origin is not in the allowed list then return 403 immediately. Also is any sensitive information is being served, validate the user via a session.

                    – Xerri
                    Sep 19 '13 at 10:52














                  • 1





                    I believe OPTIONS happens before a GET, whereas if you're doing a POST - there is no OPTIONS request...

                    – Nick
                    Sep 13 '11 at 15:14






                  • 14





                    I use app.options("*", function(req,res,next){....res.send(200)...

                    – fullstacklife
                    May 31 '12 at 3:26






                  • 21





                    Is config.allowedDomains a comma-delimited string or an array?

                    – pixelfreak
                    Nov 17 '12 at 2:56






                  • 2





                    config.allowedDomains should be a space separated array

                    – mcfedr
                    Mar 20 '13 at 8:10






                  • 1





                    The extra session was removed by simply rearranging the express middleware order. On another note, this needs a little more security. if the origin is not in the allowed domain then the request is still processed, only the browser won't be able to see it plus the origin can be spoofed. My advice would be to do a check and if the origin is not in the allowed list then return 403 immediately. Also is any sensitive information is being served, validate the user via a session.

                    – Xerri
                    Sep 19 '13 at 10:52








                  1




                  1





                  I believe OPTIONS happens before a GET, whereas if you're doing a POST - there is no OPTIONS request...

                  – Nick
                  Sep 13 '11 at 15:14





                  I believe OPTIONS happens before a GET, whereas if you're doing a POST - there is no OPTIONS request...

                  – Nick
                  Sep 13 '11 at 15:14




                  14




                  14





                  I use app.options("*", function(req,res,next){....res.send(200)...

                  – fullstacklife
                  May 31 '12 at 3:26





                  I use app.options("*", function(req,res,next){....res.send(200)...

                  – fullstacklife
                  May 31 '12 at 3:26




                  21




                  21





                  Is config.allowedDomains a comma-delimited string or an array?

                  – pixelfreak
                  Nov 17 '12 at 2:56





                  Is config.allowedDomains a comma-delimited string or an array?

                  – pixelfreak
                  Nov 17 '12 at 2:56




                  2




                  2





                  config.allowedDomains should be a space separated array

                  – mcfedr
                  Mar 20 '13 at 8:10





                  config.allowedDomains should be a space separated array

                  – mcfedr
                  Mar 20 '13 at 8:10




                  1




                  1





                  The extra session was removed by simply rearranging the express middleware order. On another note, this needs a little more security. if the origin is not in the allowed domain then the request is still processed, only the browser won't be able to see it plus the origin can be spoofed. My advice would be to do a check and if the origin is not in the allowed list then return 403 immediately. Also is any sensitive information is being served, validate the user via a session.

                  – Xerri
                  Sep 19 '13 at 10:52





                  The extra session was removed by simply rearranging the express middleware order. On another note, this needs a little more security. if the origin is not in the allowed domain then the request is still processed, only the browser won't be able to see it plus the origin can be spoofed. My advice would be to do a check and if the origin is not in the allowed list then return 403 immediately. Also is any sensitive information is being served, validate the user via a session.

                  – Xerri
                  Sep 19 '13 at 10:52











                  109














                  To stay in the same idea of routing. I use this code :



                  app.all('/*', function(req, res, next) {
                  res.header("Access-Control-Allow-Origin", "*");
                  res.header("Access-Control-Allow-Headers", "X-Requested-With");
                  next();
                  });


                  Similar to http://enable-cors.org/server_expressjs.html example






                  share|improve this answer





















                  • 1





                    This goes in the grunt.js file?

                    – Oliver Dixon
                    Jan 2 '15 at 2:13






                  • 4





                    What about preflight?

                    – backdesk
                    Feb 4 '15 at 13:01
















                  109














                  To stay in the same idea of routing. I use this code :



                  app.all('/*', function(req, res, next) {
                  res.header("Access-Control-Allow-Origin", "*");
                  res.header("Access-Control-Allow-Headers", "X-Requested-With");
                  next();
                  });


                  Similar to http://enable-cors.org/server_expressjs.html example






                  share|improve this answer





















                  • 1





                    This goes in the grunt.js file?

                    – Oliver Dixon
                    Jan 2 '15 at 2:13






                  • 4





                    What about preflight?

                    – backdesk
                    Feb 4 '15 at 13:01














                  109












                  109








                  109







                  To stay in the same idea of routing. I use this code :



                  app.all('/*', function(req, res, next) {
                  res.header("Access-Control-Allow-Origin", "*");
                  res.header("Access-Control-Allow-Headers", "X-Requested-With");
                  next();
                  });


                  Similar to http://enable-cors.org/server_expressjs.html example






                  share|improve this answer















                  To stay in the same idea of routing. I use this code :



                  app.all('/*', function(req, res, next) {
                  res.header("Access-Control-Allow-Origin", "*");
                  res.header("Access-Control-Allow-Headers", "X-Requested-With");
                  next();
                  });


                  Similar to http://enable-cors.org/server_expressjs.html example







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Oct 20 '14 at 10:12









                  Paul Verest

                  28.5k33145241




                  28.5k33145241










                  answered Feb 24 '12 at 10:46









                  LialonLialon

                  1,181176




                  1,181176








                  • 1





                    This goes in the grunt.js file?

                    – Oliver Dixon
                    Jan 2 '15 at 2:13






                  • 4





                    What about preflight?

                    – backdesk
                    Feb 4 '15 at 13:01














                  • 1





                    This goes in the grunt.js file?

                    – Oliver Dixon
                    Jan 2 '15 at 2:13






                  • 4





                    What about preflight?

                    – backdesk
                    Feb 4 '15 at 13:01








                  1




                  1





                  This goes in the grunt.js file?

                  – Oliver Dixon
                  Jan 2 '15 at 2:13





                  This goes in the grunt.js file?

                  – Oliver Dixon
                  Jan 2 '15 at 2:13




                  4




                  4





                  What about preflight?

                  – backdesk
                  Feb 4 '15 at 13:01





                  What about preflight?

                  – backdesk
                  Feb 4 '15 at 13:01











                  60














                  do



                  npm install cors --save


                  and just add these lines in your main file where your request going (keep it before any route).



                  const cors = require('cors');
                  const express = require('express');
                  let app = express();
                  app.use(cors());
                  app.options('*', cors());





                  share|improve this answer





















                  • 1





                    app.options('*', cors()) // include before other routes

                    – Rajeshwar
                    Nov 12 '18 at 10:47
















                  60














                  do



                  npm install cors --save


                  and just add these lines in your main file where your request going (keep it before any route).



                  const cors = require('cors');
                  const express = require('express');
                  let app = express();
                  app.use(cors());
                  app.options('*', cors());





                  share|improve this answer





















                  • 1





                    app.options('*', cors()) // include before other routes

                    – Rajeshwar
                    Nov 12 '18 at 10:47














                  60












                  60








                  60







                  do



                  npm install cors --save


                  and just add these lines in your main file where your request going (keep it before any route).



                  const cors = require('cors');
                  const express = require('express');
                  let app = express();
                  app.use(cors());
                  app.options('*', cors());





                  share|improve this answer















                  do



                  npm install cors --save


                  and just add these lines in your main file where your request going (keep it before any route).



                  const cors = require('cors');
                  const express = require('express');
                  let app = express();
                  app.use(cors());
                  app.options('*', cors());






                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Nov 14 '18 at 4:30

























                  answered Jul 21 '16 at 9:26









                  Yatender SinghYatender Singh

                  1,3911322




                  1,3911322








                  • 1





                    app.options('*', cors()) // include before other routes

                    – Rajeshwar
                    Nov 12 '18 at 10:47














                  • 1





                    app.options('*', cors()) // include before other routes

                    – Rajeshwar
                    Nov 12 '18 at 10:47








                  1




                  1





                  app.options('*', cors()) // include before other routes

                  – Rajeshwar
                  Nov 12 '18 at 10:47





                  app.options('*', cors()) // include before other routes

                  – Rajeshwar
                  Nov 12 '18 at 10:47











                  48














                  I have made a more complete middleware suitable for express or connect. It supports OPTIONS requests for preflight checking. Note that it will allow CORS access to anything, you might want to put in some checks if you want to limit access.



                  app.use(function(req, res, next) {
                  var oneof = false;
                  if(req.headers.origin) {
                  res.header('Access-Control-Allow-Origin', req.headers.origin);
                  oneof = true;
                  }
                  if(req.headers['access-control-request-method']) {
                  res.header('Access-Control-Allow-Methods', req.headers['access-control-request-method']);
                  oneof = true;
                  }
                  if(req.headers['access-control-request-headers']) {
                  res.header('Access-Control-Allow-Headers', req.headers['access-control-request-headers']);
                  oneof = true;
                  }
                  if(oneof) {
                  res.header('Access-Control-Max-Age', 60 * 60 * 24 * 365);
                  }

                  // intercept OPTIONS method
                  if (oneof && req.method == 'OPTIONS') {
                  res.send(200);
                  }
                  else {
                  next();
                  }
                  });





                  share|improve this answer


























                  • Hey there, I came across your solution and was wondering if the 'oneof' flag should be set false if one of the headers wasn't detected?

                    – Leonidas
                    Mar 19 '13 at 21:14






                  • 1





                    Some requests will not have all the headers. Specifically a GET request will be sent by the browser, and when it doesn't get a correct allow-origin response an error is given to js. Whereas for a POST request, the OPTIONS request is first sent, with the allow-method header, and only afterwards, the actual POST request will be sent.

                    – mcfedr
                    Mar 20 '13 at 8:06








                  • 1





                    Ah, I see. Thanks. Did you ever run into trouble by not putting res.send(200) in there if the req method was 'options'?

                    – Leonidas
                    Mar 20 '13 at 14:24













                  • I dont think i have tried sending something else, I would imagine any other response will cause the browser to refuse the request that it is preflighting.

                    – mcfedr
                    Mar 20 '13 at 15:19






                  • 1





                    omg I love you @mcfedr - a +1 doesn't capture it!

                    – ErichBSchulz
                    Mar 12 '18 at 12:56
















                  48














                  I have made a more complete middleware suitable for express or connect. It supports OPTIONS requests for preflight checking. Note that it will allow CORS access to anything, you might want to put in some checks if you want to limit access.



                  app.use(function(req, res, next) {
                  var oneof = false;
                  if(req.headers.origin) {
                  res.header('Access-Control-Allow-Origin', req.headers.origin);
                  oneof = true;
                  }
                  if(req.headers['access-control-request-method']) {
                  res.header('Access-Control-Allow-Methods', req.headers['access-control-request-method']);
                  oneof = true;
                  }
                  if(req.headers['access-control-request-headers']) {
                  res.header('Access-Control-Allow-Headers', req.headers['access-control-request-headers']);
                  oneof = true;
                  }
                  if(oneof) {
                  res.header('Access-Control-Max-Age', 60 * 60 * 24 * 365);
                  }

                  // intercept OPTIONS method
                  if (oneof && req.method == 'OPTIONS') {
                  res.send(200);
                  }
                  else {
                  next();
                  }
                  });





                  share|improve this answer


























                  • Hey there, I came across your solution and was wondering if the 'oneof' flag should be set false if one of the headers wasn't detected?

                    – Leonidas
                    Mar 19 '13 at 21:14






                  • 1





                    Some requests will not have all the headers. Specifically a GET request will be sent by the browser, and when it doesn't get a correct allow-origin response an error is given to js. Whereas for a POST request, the OPTIONS request is first sent, with the allow-method header, and only afterwards, the actual POST request will be sent.

                    – mcfedr
                    Mar 20 '13 at 8:06








                  • 1





                    Ah, I see. Thanks. Did you ever run into trouble by not putting res.send(200) in there if the req method was 'options'?

                    – Leonidas
                    Mar 20 '13 at 14:24













                  • I dont think i have tried sending something else, I would imagine any other response will cause the browser to refuse the request that it is preflighting.

                    – mcfedr
                    Mar 20 '13 at 15:19






                  • 1





                    omg I love you @mcfedr - a +1 doesn't capture it!

                    – ErichBSchulz
                    Mar 12 '18 at 12:56














                  48












                  48








                  48







                  I have made a more complete middleware suitable for express or connect. It supports OPTIONS requests for preflight checking. Note that it will allow CORS access to anything, you might want to put in some checks if you want to limit access.



                  app.use(function(req, res, next) {
                  var oneof = false;
                  if(req.headers.origin) {
                  res.header('Access-Control-Allow-Origin', req.headers.origin);
                  oneof = true;
                  }
                  if(req.headers['access-control-request-method']) {
                  res.header('Access-Control-Allow-Methods', req.headers['access-control-request-method']);
                  oneof = true;
                  }
                  if(req.headers['access-control-request-headers']) {
                  res.header('Access-Control-Allow-Headers', req.headers['access-control-request-headers']);
                  oneof = true;
                  }
                  if(oneof) {
                  res.header('Access-Control-Max-Age', 60 * 60 * 24 * 365);
                  }

                  // intercept OPTIONS method
                  if (oneof && req.method == 'OPTIONS') {
                  res.send(200);
                  }
                  else {
                  next();
                  }
                  });





                  share|improve this answer















                  I have made a more complete middleware suitable for express or connect. It supports OPTIONS requests for preflight checking. Note that it will allow CORS access to anything, you might want to put in some checks if you want to limit access.



                  app.use(function(req, res, next) {
                  var oneof = false;
                  if(req.headers.origin) {
                  res.header('Access-Control-Allow-Origin', req.headers.origin);
                  oneof = true;
                  }
                  if(req.headers['access-control-request-method']) {
                  res.header('Access-Control-Allow-Methods', req.headers['access-control-request-method']);
                  oneof = true;
                  }
                  if(req.headers['access-control-request-headers']) {
                  res.header('Access-Control-Allow-Headers', req.headers['access-control-request-headers']);
                  oneof = true;
                  }
                  if(oneof) {
                  res.header('Access-Control-Max-Age', 60 * 60 * 24 * 365);
                  }

                  // intercept OPTIONS method
                  if (oneof && req.method == 'OPTIONS') {
                  res.send(200);
                  }
                  else {
                  next();
                  }
                  });






                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Feb 6 '14 at 20:18









                  Lukas

                  8,22523145




                  8,22523145










                  answered Oct 30 '12 at 21:49









                  mcfedrmcfedr

                  5,75022225




                  5,75022225













                  • Hey there, I came across your solution and was wondering if the 'oneof' flag should be set false if one of the headers wasn't detected?

                    – Leonidas
                    Mar 19 '13 at 21:14






                  • 1





                    Some requests will not have all the headers. Specifically a GET request will be sent by the browser, and when it doesn't get a correct allow-origin response an error is given to js. Whereas for a POST request, the OPTIONS request is first sent, with the allow-method header, and only afterwards, the actual POST request will be sent.

                    – mcfedr
                    Mar 20 '13 at 8:06








                  • 1





                    Ah, I see. Thanks. Did you ever run into trouble by not putting res.send(200) in there if the req method was 'options'?

                    – Leonidas
                    Mar 20 '13 at 14:24













                  • I dont think i have tried sending something else, I would imagine any other response will cause the browser to refuse the request that it is preflighting.

                    – mcfedr
                    Mar 20 '13 at 15:19






                  • 1





                    omg I love you @mcfedr - a +1 doesn't capture it!

                    – ErichBSchulz
                    Mar 12 '18 at 12:56



















                  • Hey there, I came across your solution and was wondering if the 'oneof' flag should be set false if one of the headers wasn't detected?

                    – Leonidas
                    Mar 19 '13 at 21:14






                  • 1





                    Some requests will not have all the headers. Specifically a GET request will be sent by the browser, and when it doesn't get a correct allow-origin response an error is given to js. Whereas for a POST request, the OPTIONS request is first sent, with the allow-method header, and only afterwards, the actual POST request will be sent.

                    – mcfedr
                    Mar 20 '13 at 8:06








                  • 1





                    Ah, I see. Thanks. Did you ever run into trouble by not putting res.send(200) in there if the req method was 'options'?

                    – Leonidas
                    Mar 20 '13 at 14:24













                  • I dont think i have tried sending something else, I would imagine any other response will cause the browser to refuse the request that it is preflighting.

                    – mcfedr
                    Mar 20 '13 at 15:19






                  • 1





                    omg I love you @mcfedr - a +1 doesn't capture it!

                    – ErichBSchulz
                    Mar 12 '18 at 12:56

















                  Hey there, I came across your solution and was wondering if the 'oneof' flag should be set false if one of the headers wasn't detected?

                  – Leonidas
                  Mar 19 '13 at 21:14





                  Hey there, I came across your solution and was wondering if the 'oneof' flag should be set false if one of the headers wasn't detected?

                  – Leonidas
                  Mar 19 '13 at 21:14




                  1




                  1





                  Some requests will not have all the headers. Specifically a GET request will be sent by the browser, and when it doesn't get a correct allow-origin response an error is given to js. Whereas for a POST request, the OPTIONS request is first sent, with the allow-method header, and only afterwards, the actual POST request will be sent.

                  – mcfedr
                  Mar 20 '13 at 8:06







                  Some requests will not have all the headers. Specifically a GET request will be sent by the browser, and when it doesn't get a correct allow-origin response an error is given to js. Whereas for a POST request, the OPTIONS request is first sent, with the allow-method header, and only afterwards, the actual POST request will be sent.

                  – mcfedr
                  Mar 20 '13 at 8:06






                  1




                  1





                  Ah, I see. Thanks. Did you ever run into trouble by not putting res.send(200) in there if the req method was 'options'?

                  – Leonidas
                  Mar 20 '13 at 14:24







                  Ah, I see. Thanks. Did you ever run into trouble by not putting res.send(200) in there if the req method was 'options'?

                  – Leonidas
                  Mar 20 '13 at 14:24















                  I dont think i have tried sending something else, I would imagine any other response will cause the browser to refuse the request that it is preflighting.

                  – mcfedr
                  Mar 20 '13 at 15:19





                  I dont think i have tried sending something else, I would imagine any other response will cause the browser to refuse the request that it is preflighting.

                  – mcfedr
                  Mar 20 '13 at 15:19




                  1




                  1





                  omg I love you @mcfedr - a +1 doesn't capture it!

                  – ErichBSchulz
                  Mar 12 '18 at 12:56





                  omg I love you @mcfedr - a +1 doesn't capture it!

                  – ErichBSchulz
                  Mar 12 '18 at 12:56











                  33














                  install cors module of expressjs. you can follow these steps >



                  Installation



                  npm install cors


                  Simple Usage (Enable All CORS Requests)



                  var express = require('express');
                  var cors = require('cors');
                  var app = express();
                  app.use(cors());


                  for more details go to https://github.com/expressjs/cors






                  share|improve this answer



















                  • 2





                    TypeError: Cannot read property 'headers' of undefined The most basic app setup.

                    – Oliver Dixon
                    Dec 3 '17 at 19:51













                  • Are you sure you have request object ? :)

                    – codebased
                    Apr 12 '18 at 23:25
















                  33














                  install cors module of expressjs. you can follow these steps >



                  Installation



                  npm install cors


                  Simple Usage (Enable All CORS Requests)



                  var express = require('express');
                  var cors = require('cors');
                  var app = express();
                  app.use(cors());


                  for more details go to https://github.com/expressjs/cors






                  share|improve this answer



















                  • 2





                    TypeError: Cannot read property 'headers' of undefined The most basic app setup.

                    – Oliver Dixon
                    Dec 3 '17 at 19:51













                  • Are you sure you have request object ? :)

                    – codebased
                    Apr 12 '18 at 23:25














                  33












                  33








                  33







                  install cors module of expressjs. you can follow these steps >



                  Installation



                  npm install cors


                  Simple Usage (Enable All CORS Requests)



                  var express = require('express');
                  var cors = require('cors');
                  var app = express();
                  app.use(cors());


                  for more details go to https://github.com/expressjs/cors






                  share|improve this answer













                  install cors module of expressjs. you can follow these steps >



                  Installation



                  npm install cors


                  Simple Usage (Enable All CORS Requests)



                  var express = require('express');
                  var cors = require('cors');
                  var app = express();
                  app.use(cors());


                  for more details go to https://github.com/expressjs/cors







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Jun 15 '16 at 20:37









                  rahuL islamrahuL islam

                  33335




                  33335








                  • 2





                    TypeError: Cannot read property 'headers' of undefined The most basic app setup.

                    – Oliver Dixon
                    Dec 3 '17 at 19:51













                  • Are you sure you have request object ? :)

                    – codebased
                    Apr 12 '18 at 23:25














                  • 2





                    TypeError: Cannot read property 'headers' of undefined The most basic app setup.

                    – Oliver Dixon
                    Dec 3 '17 at 19:51













                  • Are you sure you have request object ? :)

                    – codebased
                    Apr 12 '18 at 23:25








                  2




                  2





                  TypeError: Cannot read property 'headers' of undefined The most basic app setup.

                  – Oliver Dixon
                  Dec 3 '17 at 19:51







                  TypeError: Cannot read property 'headers' of undefined The most basic app setup.

                  – Oliver Dixon
                  Dec 3 '17 at 19:51















                  Are you sure you have request object ? :)

                  – codebased
                  Apr 12 '18 at 23:25





                  Are you sure you have request object ? :)

                  – codebased
                  Apr 12 '18 at 23:25











                  29














                  Do something like this:



                  app.use(function(req, res, next) {
                  res.header("Access-Control-Allow-Origin", "*");
                  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
                  next();
                  });





                  share|improve this answer



















                  • 3





                    this is the solution on enable-cors.org/server_expressjs.html

                    – Z. Khullah
                    Nov 12 '16 at 19:38
















                  29














                  Do something like this:



                  app.use(function(req, res, next) {
                  res.header("Access-Control-Allow-Origin", "*");
                  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
                  next();
                  });





                  share|improve this answer



















                  • 3





                    this is the solution on enable-cors.org/server_expressjs.html

                    – Z. Khullah
                    Nov 12 '16 at 19:38














                  29












                  29








                  29







                  Do something like this:



                  app.use(function(req, res, next) {
                  res.header("Access-Control-Allow-Origin", "*");
                  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
                  next();
                  });





                  share|improve this answer













                  Do something like this:



                  app.use(function(req, res, next) {
                  res.header("Access-Control-Allow-Origin", "*");
                  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
                  next();
                  });






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Jan 3 '16 at 8:24









                  RussRuss

                  34635




                  34635








                  • 3





                    this is the solution on enable-cors.org/server_expressjs.html

                    – Z. Khullah
                    Nov 12 '16 at 19:38














                  • 3





                    this is the solution on enable-cors.org/server_expressjs.html

                    – Z. Khullah
                    Nov 12 '16 at 19:38








                  3




                  3





                  this is the solution on enable-cors.org/server_expressjs.html

                  – Z. Khullah
                  Nov 12 '16 at 19:38





                  this is the solution on enable-cors.org/server_expressjs.html

                  – Z. Khullah
                  Nov 12 '16 at 19:38











                  19














                  Testing done with express + node + ionic running in differente ports.



                  Localhost:8100



                  Localhost:5000



                  // CORS (Cross-Origin Resource Sharing) headers to support Cross-site HTTP requests

                  app.all('*', function(req, res, next) {
                  res.header("Access-Control-Allow-Origin", "*");
                  res.header("Access-Control-Allow-Headers", "X-Requested-With");
                  res.header('Access-Control-Allow-Headers', 'Content-Type');
                  next();
                  });





                  share|improve this answer





















                  • 2





                    In which file do we need to add this lines?

                    – Shefalee Chaudhary
                    Dec 15 '16 at 10:24
















                  19














                  Testing done with express + node + ionic running in differente ports.



                  Localhost:8100



                  Localhost:5000



                  // CORS (Cross-Origin Resource Sharing) headers to support Cross-site HTTP requests

                  app.all('*', function(req, res, next) {
                  res.header("Access-Control-Allow-Origin", "*");
                  res.header("Access-Control-Allow-Headers", "X-Requested-With");
                  res.header('Access-Control-Allow-Headers', 'Content-Type');
                  next();
                  });





                  share|improve this answer





















                  • 2





                    In which file do we need to add this lines?

                    – Shefalee Chaudhary
                    Dec 15 '16 at 10:24














                  19












                  19








                  19







                  Testing done with express + node + ionic running in differente ports.



                  Localhost:8100



                  Localhost:5000



                  // CORS (Cross-Origin Resource Sharing) headers to support Cross-site HTTP requests

                  app.all('*', function(req, res, next) {
                  res.header("Access-Control-Allow-Origin", "*");
                  res.header("Access-Control-Allow-Headers", "X-Requested-With");
                  res.header('Access-Control-Allow-Headers', 'Content-Type');
                  next();
                  });





                  share|improve this answer















                  Testing done with express + node + ionic running in differente ports.



                  Localhost:8100



                  Localhost:5000



                  // CORS (Cross-Origin Resource Sharing) headers to support Cross-site HTTP requests

                  app.all('*', function(req, res, next) {
                  res.header("Access-Control-Allow-Origin", "*");
                  res.header("Access-Control-Allow-Headers", "X-Requested-With");
                  res.header('Access-Control-Allow-Headers', 'Content-Type');
                  next();
                  });






                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Nov 8 '14 at 20:55









                  PitaJ

                  4,23852045




                  4,23852045










                  answered Nov 8 '14 at 20:35









                  Daniel LaurindoDaniel Laurindo

                  81484




                  81484








                  • 2





                    In which file do we need to add this lines?

                    – Shefalee Chaudhary
                    Dec 15 '16 at 10:24














                  • 2





                    In which file do we need to add this lines?

                    – Shefalee Chaudhary
                    Dec 15 '16 at 10:24








                  2




                  2





                  In which file do we need to add this lines?

                  – Shefalee Chaudhary
                  Dec 15 '16 at 10:24





                  In which file do we need to add this lines?

                  – Shefalee Chaudhary
                  Dec 15 '16 at 10:24











                  19














                  first simply install cors in your project.
                  Take terminal(command prompt) and cd to your project directory and run the below command:



                  npm install cors --save


                  Then take the server.js file and change the code to add the following in it:



                  var cors = require('cors');


                  var app = express();

                  app.use(cors());

                  app.use(function(req, res, next) {
                  res.header("Access-Control-Allow-Origin", "*");
                  res.header('Access-Control-Allow-Methods', 'DELETE, PUT, GET, POST');
                  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
                  next();
                  });


                  This worked for me..






                  share|improve this answer





















                  • 2





                    You don't need cors if you're doing the res.header stuff. cors is a library that handles all that for you. Delete your first & 3rd lines (AKA everything with cors) and you'll find that it still works.

                    – thisissami
                    Sep 7 '17 at 19:25











                  • heck i'm pretty sure all you really need is this line res.header("Access-Control-Allow-Origin", "*");

                    – thisissami
                    Sep 7 '17 at 19:26











                  • though do keep in mind that you're compromising your security by doing that. :)

                    – thisissami
                    Sep 7 '17 at 19:27
















                  19














                  first simply install cors in your project.
                  Take terminal(command prompt) and cd to your project directory and run the below command:



                  npm install cors --save


                  Then take the server.js file and change the code to add the following in it:



                  var cors = require('cors');


                  var app = express();

                  app.use(cors());

                  app.use(function(req, res, next) {
                  res.header("Access-Control-Allow-Origin", "*");
                  res.header('Access-Control-Allow-Methods', 'DELETE, PUT, GET, POST');
                  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
                  next();
                  });


                  This worked for me..






                  share|improve this answer





















                  • 2





                    You don't need cors if you're doing the res.header stuff. cors is a library that handles all that for you. Delete your first & 3rd lines (AKA everything with cors) and you'll find that it still works.

                    – thisissami
                    Sep 7 '17 at 19:25











                  • heck i'm pretty sure all you really need is this line res.header("Access-Control-Allow-Origin", "*");

                    – thisissami
                    Sep 7 '17 at 19:26











                  • though do keep in mind that you're compromising your security by doing that. :)

                    – thisissami
                    Sep 7 '17 at 19:27














                  19












                  19








                  19







                  first simply install cors in your project.
                  Take terminal(command prompt) and cd to your project directory and run the below command:



                  npm install cors --save


                  Then take the server.js file and change the code to add the following in it:



                  var cors = require('cors');


                  var app = express();

                  app.use(cors());

                  app.use(function(req, res, next) {
                  res.header("Access-Control-Allow-Origin", "*");
                  res.header('Access-Control-Allow-Methods', 'DELETE, PUT, GET, POST');
                  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
                  next();
                  });


                  This worked for me..






                  share|improve this answer















                  first simply install cors in your project.
                  Take terminal(command prompt) and cd to your project directory and run the below command:



                  npm install cors --save


                  Then take the server.js file and change the code to add the following in it:



                  var cors = require('cors');


                  var app = express();

                  app.use(cors());

                  app.use(function(req, res, next) {
                  res.header("Access-Control-Allow-Origin", "*");
                  res.header('Access-Control-Allow-Methods', 'DELETE, PUT, GET, POST');
                  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
                  next();
                  });


                  This worked for me..







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Sep 16 '17 at 22:37









                  teliz

                  310212




                  310212










                  answered Sep 5 '17 at 9:08









                  Reneesh TKReneesh TK

                  21722




                  21722








                  • 2





                    You don't need cors if you're doing the res.header stuff. cors is a library that handles all that for you. Delete your first & 3rd lines (AKA everything with cors) and you'll find that it still works.

                    – thisissami
                    Sep 7 '17 at 19:25











                  • heck i'm pretty sure all you really need is this line res.header("Access-Control-Allow-Origin", "*");

                    – thisissami
                    Sep 7 '17 at 19:26











                  • though do keep in mind that you're compromising your security by doing that. :)

                    – thisissami
                    Sep 7 '17 at 19:27














                  • 2





                    You don't need cors if you're doing the res.header stuff. cors is a library that handles all that for you. Delete your first & 3rd lines (AKA everything with cors) and you'll find that it still works.

                    – thisissami
                    Sep 7 '17 at 19:25











                  • heck i'm pretty sure all you really need is this line res.header("Access-Control-Allow-Origin", "*");

                    – thisissami
                    Sep 7 '17 at 19:26











                  • though do keep in mind that you're compromising your security by doing that. :)

                    – thisissami
                    Sep 7 '17 at 19:27








                  2




                  2





                  You don't need cors if you're doing the res.header stuff. cors is a library that handles all that for you. Delete your first & 3rd lines (AKA everything with cors) and you'll find that it still works.

                  – thisissami
                  Sep 7 '17 at 19:25





                  You don't need cors if you're doing the res.header stuff. cors is a library that handles all that for you. Delete your first & 3rd lines (AKA everything with cors) and you'll find that it still works.

                  – thisissami
                  Sep 7 '17 at 19:25













                  heck i'm pretty sure all you really need is this line res.header("Access-Control-Allow-Origin", "*");

                  – thisissami
                  Sep 7 '17 at 19:26





                  heck i'm pretty sure all you really need is this line res.header("Access-Control-Allow-Origin", "*");

                  – thisissami
                  Sep 7 '17 at 19:26













                  though do keep in mind that you're compromising your security by doing that. :)

                  – thisissami
                  Sep 7 '17 at 19:27





                  though do keep in mind that you're compromising your security by doing that. :)

                  – thisissami
                  Sep 7 '17 at 19:27











                  10














                  This works for me, as its an easy implementation inside the routes, im using meanjs and its working fine, safari, chrome, etc.



                  app.route('/footer-contact-form').post(emailer.sendFooterMail).options(function(req,res,next){ 
                  res.header('Access-Control-Allow-Origin', '*');
                  res.header('Access-Control-Allow-Methods', 'GET, POST');
                  res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
                  return res.send(200);

                  });





                  share|improve this answer




























                    10














                    This works for me, as its an easy implementation inside the routes, im using meanjs and its working fine, safari, chrome, etc.



                    app.route('/footer-contact-form').post(emailer.sendFooterMail).options(function(req,res,next){ 
                    res.header('Access-Control-Allow-Origin', '*');
                    res.header('Access-Control-Allow-Methods', 'GET, POST');
                    res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
                    return res.send(200);

                    });





                    share|improve this answer


























                      10












                      10








                      10







                      This works for me, as its an easy implementation inside the routes, im using meanjs and its working fine, safari, chrome, etc.



                      app.route('/footer-contact-form').post(emailer.sendFooterMail).options(function(req,res,next){ 
                      res.header('Access-Control-Allow-Origin', '*');
                      res.header('Access-Control-Allow-Methods', 'GET, POST');
                      res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
                      return res.send(200);

                      });





                      share|improve this answer













                      This works for me, as its an easy implementation inside the routes, im using meanjs and its working fine, safari, chrome, etc.



                      app.route('/footer-contact-form').post(emailer.sendFooterMail).options(function(req,res,next){ 
                      res.header('Access-Control-Allow-Origin', '*');
                      res.header('Access-Control-Allow-Methods', 'GET, POST');
                      res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
                      return res.send(200);

                      });






                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered Aug 24 '15 at 20:13









                      Kiko SeijoKiko Seijo

                      43559




                      43559























                          9














                          Some time ago, I faced this problem so I did this to allow CORS in my nodejs app:



                          First you need to install cors by using below command :



                          npm install cors --save


                          Now add the following code to your app starting file like ( app.js or server.js)



                          var express = require('express');
                          var app = express();

                          var cors = require('cors');
                          var bodyParser = require('body-parser');

                          //enables cors
                          app.use(cors({
                          'allowedHeaders': ['sessionId', 'Content-Type'],
                          'exposedHeaders': ['sessionId'],
                          'origin': '*',
                          'methods': 'GET,HEAD,PUT,PATCH,POST,DELETE',
                          'preflightContinue': false
                          }));

                          require('./router/index')(app);





                          share|improve this answer


























                          • This is the only part of code from my app.js.

                            – Shubham Verma
                            Jan 24 '17 at 10:20











                          • tried this after installing cors. Cors is not a function

                            – colin rickels
                            Jul 6 '18 at 13:27
















                          9














                          Some time ago, I faced this problem so I did this to allow CORS in my nodejs app:



                          First you need to install cors by using below command :



                          npm install cors --save


                          Now add the following code to your app starting file like ( app.js or server.js)



                          var express = require('express');
                          var app = express();

                          var cors = require('cors');
                          var bodyParser = require('body-parser');

                          //enables cors
                          app.use(cors({
                          'allowedHeaders': ['sessionId', 'Content-Type'],
                          'exposedHeaders': ['sessionId'],
                          'origin': '*',
                          'methods': 'GET,HEAD,PUT,PATCH,POST,DELETE',
                          'preflightContinue': false
                          }));

                          require('./router/index')(app);





                          share|improve this answer


























                          • This is the only part of code from my app.js.

                            – Shubham Verma
                            Jan 24 '17 at 10:20











                          • tried this after installing cors. Cors is not a function

                            – colin rickels
                            Jul 6 '18 at 13:27














                          9












                          9








                          9







                          Some time ago, I faced this problem so I did this to allow CORS in my nodejs app:



                          First you need to install cors by using below command :



                          npm install cors --save


                          Now add the following code to your app starting file like ( app.js or server.js)



                          var express = require('express');
                          var app = express();

                          var cors = require('cors');
                          var bodyParser = require('body-parser');

                          //enables cors
                          app.use(cors({
                          'allowedHeaders': ['sessionId', 'Content-Type'],
                          'exposedHeaders': ['sessionId'],
                          'origin': '*',
                          'methods': 'GET,HEAD,PUT,PATCH,POST,DELETE',
                          'preflightContinue': false
                          }));

                          require('./router/index')(app);





                          share|improve this answer















                          Some time ago, I faced this problem so I did this to allow CORS in my nodejs app:



                          First you need to install cors by using below command :



                          npm install cors --save


                          Now add the following code to your app starting file like ( app.js or server.js)



                          var express = require('express');
                          var app = express();

                          var cors = require('cors');
                          var bodyParser = require('body-parser');

                          //enables cors
                          app.use(cors({
                          'allowedHeaders': ['sessionId', 'Content-Type'],
                          'exposedHeaders': ['sessionId'],
                          'origin': '*',
                          'methods': 'GET,HEAD,PUT,PATCH,POST,DELETE',
                          'preflightContinue': false
                          }));

                          require('./router/index')(app);






                          share|improve this answer














                          share|improve this answer



                          share|improve this answer








                          edited May 1 '18 at 5:55

























                          answered Jan 24 '17 at 10:19









                          Shubham VermaShubham Verma

                          2,53622551




                          2,53622551













                          • This is the only part of code from my app.js.

                            – Shubham Verma
                            Jan 24 '17 at 10:20











                          • tried this after installing cors. Cors is not a function

                            – colin rickels
                            Jul 6 '18 at 13:27



















                          • This is the only part of code from my app.js.

                            – Shubham Verma
                            Jan 24 '17 at 10:20











                          • tried this after installing cors. Cors is not a function

                            – colin rickels
                            Jul 6 '18 at 13:27

















                          This is the only part of code from my app.js.

                          – Shubham Verma
                          Jan 24 '17 at 10:20





                          This is the only part of code from my app.js.

                          – Shubham Verma
                          Jan 24 '17 at 10:20













                          tried this after installing cors. Cors is not a function

                          – colin rickels
                          Jul 6 '18 at 13:27





                          tried this after installing cors. Cors is not a function

                          – colin rickels
                          Jul 6 '18 at 13:27











                          7














                          If you want to make it controller specific, you can use:



                          res.setHeader('X-Frame-Options', 'ALLOWALL');
                          res.setHeader('Access-Control-Allow-Origin', '*');
                          res.setHeader('Access-Control-Allow-Methods', 'POST, GET');
                          res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');


                          Please note that this will also allow iframes.






                          share|improve this answer




























                            7














                            If you want to make it controller specific, you can use:



                            res.setHeader('X-Frame-Options', 'ALLOWALL');
                            res.setHeader('Access-Control-Allow-Origin', '*');
                            res.setHeader('Access-Control-Allow-Methods', 'POST, GET');
                            res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');


                            Please note that this will also allow iframes.






                            share|improve this answer


























                              7












                              7








                              7







                              If you want to make it controller specific, you can use:



                              res.setHeader('X-Frame-Options', 'ALLOWALL');
                              res.setHeader('Access-Control-Allow-Origin', '*');
                              res.setHeader('Access-Control-Allow-Methods', 'POST, GET');
                              res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');


                              Please note that this will also allow iframes.






                              share|improve this answer













                              If you want to make it controller specific, you can use:



                              res.setHeader('X-Frame-Options', 'ALLOWALL');
                              res.setHeader('Access-Control-Allow-Origin', '*');
                              res.setHeader('Access-Control-Allow-Methods', 'POST, GET');
                              res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');


                              Please note that this will also allow iframes.







                              share|improve this answer












                              share|improve this answer



                              share|improve this answer










                              answered Jan 5 '18 at 22:01









                              Koray GocmenKoray Gocmen

                              279213




                              279213























                                  4














                                  Can refer the code below for the same. Source: Academind/node-restful-api



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

                                  //acts as a middleware
                                  //to handle CORS Errors
                                  app.use((req, res, next) => { //doesn't send response just adjusts it
                                  res.header("Access-Control-Allow-Origin", "*") //* to give access to any origin
                                  res.header(
                                  "Access-Control-Allow-Headers",
                                  "Origin, X-Requested-With, Content-Type, Accept, Authorization" //to give access to all the headers provided
                                  );
                                  if(req.method === 'OPTIONS'){
                                  res.header('Access-Control-Allow-Methods', 'PUT, POST, PATCH, DELETE, GET'); //to give access to all the methods provided
                                  return res.status(200).json({});
                                  }
                                  next(); //so that other routes can take over
                                  })





                                  share|improve this answer
























                                  • I saw many answer and this have something which is importan, I tried to use this part of the code after some other configurations and it didn't work and for some reason, I tried putting the code after app const app = express(); and works! I think is important to mention it.

                                    – rfcabal
                                    Jan 13 at 0:45
















                                  4














                                  Can refer the code below for the same. Source: Academind/node-restful-api



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

                                  //acts as a middleware
                                  //to handle CORS Errors
                                  app.use((req, res, next) => { //doesn't send response just adjusts it
                                  res.header("Access-Control-Allow-Origin", "*") //* to give access to any origin
                                  res.header(
                                  "Access-Control-Allow-Headers",
                                  "Origin, X-Requested-With, Content-Type, Accept, Authorization" //to give access to all the headers provided
                                  );
                                  if(req.method === 'OPTIONS'){
                                  res.header('Access-Control-Allow-Methods', 'PUT, POST, PATCH, DELETE, GET'); //to give access to all the methods provided
                                  return res.status(200).json({});
                                  }
                                  next(); //so that other routes can take over
                                  })





                                  share|improve this answer
























                                  • I saw many answer and this have something which is importan, I tried to use this part of the code after some other configurations and it didn't work and for some reason, I tried putting the code after app const app = express(); and works! I think is important to mention it.

                                    – rfcabal
                                    Jan 13 at 0:45














                                  4












                                  4








                                  4







                                  Can refer the code below for the same. Source: Academind/node-restful-api



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

                                  //acts as a middleware
                                  //to handle CORS Errors
                                  app.use((req, res, next) => { //doesn't send response just adjusts it
                                  res.header("Access-Control-Allow-Origin", "*") //* to give access to any origin
                                  res.header(
                                  "Access-Control-Allow-Headers",
                                  "Origin, X-Requested-With, Content-Type, Accept, Authorization" //to give access to all the headers provided
                                  );
                                  if(req.method === 'OPTIONS'){
                                  res.header('Access-Control-Allow-Methods', 'PUT, POST, PATCH, DELETE, GET'); //to give access to all the methods provided
                                  return res.status(200).json({});
                                  }
                                  next(); //so that other routes can take over
                                  })





                                  share|improve this answer













                                  Can refer the code below for the same. Source: Academind/node-restful-api



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

                                  //acts as a middleware
                                  //to handle CORS Errors
                                  app.use((req, res, next) => { //doesn't send response just adjusts it
                                  res.header("Access-Control-Allow-Origin", "*") //* to give access to any origin
                                  res.header(
                                  "Access-Control-Allow-Headers",
                                  "Origin, X-Requested-With, Content-Type, Accept, Authorization" //to give access to all the headers provided
                                  );
                                  if(req.method === 'OPTIONS'){
                                  res.header('Access-Control-Allow-Methods', 'PUT, POST, PATCH, DELETE, GET'); //to give access to all the methods provided
                                  return res.status(200).json({});
                                  }
                                  next(); //so that other routes can take over
                                  })






                                  share|improve this answer












                                  share|improve this answer



                                  share|improve this answer










                                  answered Sep 25 '18 at 12:29









                                  Gadhia ReemaGadhia Reema

                                  12911




                                  12911













                                  • I saw many answer and this have something which is importan, I tried to use this part of the code after some other configurations and it didn't work and for some reason, I tried putting the code after app const app = express(); and works! I think is important to mention it.

                                    – rfcabal
                                    Jan 13 at 0:45



















                                  • I saw many answer and this have something which is importan, I tried to use this part of the code after some other configurations and it didn't work and for some reason, I tried putting the code after app const app = express(); and works! I think is important to mention it.

                                    – rfcabal
                                    Jan 13 at 0:45

















                                  I saw many answer and this have something which is importan, I tried to use this part of the code after some other configurations and it didn't work and for some reason, I tried putting the code after app const app = express(); and works! I think is important to mention it.

                                  – rfcabal
                                  Jan 13 at 0:45





                                  I saw many answer and this have something which is importan, I tried to use this part of the code after some other configurations and it didn't work and for some reason, I tried putting the code after app const app = express(); and works! I think is important to mention it.

                                  – rfcabal
                                  Jan 13 at 0:45











                                  3














                                  My simplest solution with Express 4.2.0 (EDIT: Doesn't seem to work in 4.3.0) was:



                                  function supportCrossOriginScript(req, res, next) {
                                  res.status(200);
                                  res.header("Access-Control-Allow-Origin", "*");
                                  res.header("Access-Control-Allow-Headers", "Content-Type");

                                  // res.header("Access-Control-Allow-Headers", "Origin");
                                  // res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
                                  // res.header("Access-Control-Allow-Methods","POST, OPTIONS");
                                  // res.header("Access-Control-Allow-Methods","POST, GET, OPTIONS, DELETE, PUT, HEAD");
                                  // res.header("Access-Control-Max-Age","1728000");
                                  next();
                                  }

                                  // Support CORS
                                  app.options('/result', supportCrossOriginScript);

                                  app.post('/result', supportCrossOriginScript, function(req, res) {
                                  res.send('received');
                                  // do stuff with req
                                  });


                                  I suppose doing app.all('/result', ...) would work too...






                                  share|improve this answer






























                                    3














                                    My simplest solution with Express 4.2.0 (EDIT: Doesn't seem to work in 4.3.0) was:



                                    function supportCrossOriginScript(req, res, next) {
                                    res.status(200);
                                    res.header("Access-Control-Allow-Origin", "*");
                                    res.header("Access-Control-Allow-Headers", "Content-Type");

                                    // res.header("Access-Control-Allow-Headers", "Origin");
                                    // res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
                                    // res.header("Access-Control-Allow-Methods","POST, OPTIONS");
                                    // res.header("Access-Control-Allow-Methods","POST, GET, OPTIONS, DELETE, PUT, HEAD");
                                    // res.header("Access-Control-Max-Age","1728000");
                                    next();
                                    }

                                    // Support CORS
                                    app.options('/result', supportCrossOriginScript);

                                    app.post('/result', supportCrossOriginScript, function(req, res) {
                                    res.send('received');
                                    // do stuff with req
                                    });


                                    I suppose doing app.all('/result', ...) would work too...






                                    share|improve this answer




























                                      3












                                      3








                                      3







                                      My simplest solution with Express 4.2.0 (EDIT: Doesn't seem to work in 4.3.0) was:



                                      function supportCrossOriginScript(req, res, next) {
                                      res.status(200);
                                      res.header("Access-Control-Allow-Origin", "*");
                                      res.header("Access-Control-Allow-Headers", "Content-Type");

                                      // res.header("Access-Control-Allow-Headers", "Origin");
                                      // res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
                                      // res.header("Access-Control-Allow-Methods","POST, OPTIONS");
                                      // res.header("Access-Control-Allow-Methods","POST, GET, OPTIONS, DELETE, PUT, HEAD");
                                      // res.header("Access-Control-Max-Age","1728000");
                                      next();
                                      }

                                      // Support CORS
                                      app.options('/result', supportCrossOriginScript);

                                      app.post('/result', supportCrossOriginScript, function(req, res) {
                                      res.send('received');
                                      // do stuff with req
                                      });


                                      I suppose doing app.all('/result', ...) would work too...






                                      share|improve this answer















                                      My simplest solution with Express 4.2.0 (EDIT: Doesn't seem to work in 4.3.0) was:



                                      function supportCrossOriginScript(req, res, next) {
                                      res.status(200);
                                      res.header("Access-Control-Allow-Origin", "*");
                                      res.header("Access-Control-Allow-Headers", "Content-Type");

                                      // res.header("Access-Control-Allow-Headers", "Origin");
                                      // res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
                                      // res.header("Access-Control-Allow-Methods","POST, OPTIONS");
                                      // res.header("Access-Control-Allow-Methods","POST, GET, OPTIONS, DELETE, PUT, HEAD");
                                      // res.header("Access-Control-Max-Age","1728000");
                                      next();
                                      }

                                      // Support CORS
                                      app.options('/result', supportCrossOriginScript);

                                      app.post('/result', supportCrossOriginScript, function(req, res) {
                                      res.send('received');
                                      // do stuff with req
                                      });


                                      I suppose doing app.all('/result', ...) would work too...







                                      share|improve this answer














                                      share|improve this answer



                                      share|improve this answer








                                      edited May 22 '14 at 18:13

























                                      answered May 5 '14 at 23:47









                                      PatPat

                                      9,977106897




                                      9,977106897























                                          3














                                          In addition to what others have said, don't forget that unless using nodemon you will need to restart your node server for the changes to take effect!



                                          I personally had been refreshing my browser out of habit, forgetting that it's server side code.






                                          share|improve this answer




























                                            3














                                            In addition to what others have said, don't forget that unless using nodemon you will need to restart your node server for the changes to take effect!



                                            I personally had been refreshing my browser out of habit, forgetting that it's server side code.






                                            share|improve this answer


























                                              3












                                              3








                                              3







                                              In addition to what others have said, don't forget that unless using nodemon you will need to restart your node server for the changes to take effect!



                                              I personally had been refreshing my browser out of habit, forgetting that it's server side code.






                                              share|improve this answer













                                              In addition to what others have said, don't forget that unless using nodemon you will need to restart your node server for the changes to take effect!



                                              I personally had been refreshing my browser out of habit, forgetting that it's server side code.







                                              share|improve this answer












                                              share|improve this answer



                                              share|improve this answer










                                              answered Mar 25 '16 at 12:51









                                              camjocotemcamjocotem

                                              5818




                                              5818























                                                  2














                                                  I found it to be extremely easy to do this with the npm request package (https://www.npmjs.com/package/request)



                                                  Then I based my solution on this post http://blog.javascripting.com/2015/01/17/dont-hassle-with-cors/



                                                  'use strict'

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

                                                  let proxyConfig = {
                                                  url : {
                                                  base: 'http://servertoreach.com?id=',
                                                  }
                                                  }

                                                  /* setting up and configuring node express server for the application */
                                                  let server = express();
                                                  server.set('port', 3000);


                                                  /* methods forwarded to the servertoreach proxy */
                                                  server.use('/somethingElse', function(req, res)
                                                  {
                                                  let url = proxyConfig.url.base + req.query.id;
                                                  req.pipe(request(url)).pipe(res);
                                                  });


                                                  /* start the server */
                                                  server.listen(server.get('port'), function() {
                                                  console.log('express server with a proxy listening on port ' + server.get('port'));
                                                  });





                                                  share|improve this answer




























                                                    2














                                                    I found it to be extremely easy to do this with the npm request package (https://www.npmjs.com/package/request)



                                                    Then I based my solution on this post http://blog.javascripting.com/2015/01/17/dont-hassle-with-cors/



                                                    'use strict'

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

                                                    let proxyConfig = {
                                                    url : {
                                                    base: 'http://servertoreach.com?id=',
                                                    }
                                                    }

                                                    /* setting up and configuring node express server for the application */
                                                    let server = express();
                                                    server.set('port', 3000);


                                                    /* methods forwarded to the servertoreach proxy */
                                                    server.use('/somethingElse', function(req, res)
                                                    {
                                                    let url = proxyConfig.url.base + req.query.id;
                                                    req.pipe(request(url)).pipe(res);
                                                    });


                                                    /* start the server */
                                                    server.listen(server.get('port'), function() {
                                                    console.log('express server with a proxy listening on port ' + server.get('port'));
                                                    });





                                                    share|improve this answer


























                                                      2












                                                      2








                                                      2







                                                      I found it to be extremely easy to do this with the npm request package (https://www.npmjs.com/package/request)



                                                      Then I based my solution on this post http://blog.javascripting.com/2015/01/17/dont-hassle-with-cors/



                                                      'use strict'

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

                                                      let proxyConfig = {
                                                      url : {
                                                      base: 'http://servertoreach.com?id=',
                                                      }
                                                      }

                                                      /* setting up and configuring node express server for the application */
                                                      let server = express();
                                                      server.set('port', 3000);


                                                      /* methods forwarded to the servertoreach proxy */
                                                      server.use('/somethingElse', function(req, res)
                                                      {
                                                      let url = proxyConfig.url.base + req.query.id;
                                                      req.pipe(request(url)).pipe(res);
                                                      });


                                                      /* start the server */
                                                      server.listen(server.get('port'), function() {
                                                      console.log('express server with a proxy listening on port ' + server.get('port'));
                                                      });





                                                      share|improve this answer













                                                      I found it to be extremely easy to do this with the npm request package (https://www.npmjs.com/package/request)



                                                      Then I based my solution on this post http://blog.javascripting.com/2015/01/17/dont-hassle-with-cors/



                                                      'use strict'

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

                                                      let proxyConfig = {
                                                      url : {
                                                      base: 'http://servertoreach.com?id=',
                                                      }
                                                      }

                                                      /* setting up and configuring node express server for the application */
                                                      let server = express();
                                                      server.set('port', 3000);


                                                      /* methods forwarded to the servertoreach proxy */
                                                      server.use('/somethingElse', function(req, res)
                                                      {
                                                      let url = proxyConfig.url.base + req.query.id;
                                                      req.pipe(request(url)).pipe(res);
                                                      });


                                                      /* start the server */
                                                      server.listen(server.get('port'), function() {
                                                      console.log('express server with a proxy listening on port ' + server.get('port'));
                                                      });






                                                      share|improve this answer












                                                      share|improve this answer



                                                      share|improve this answer










                                                      answered Feb 10 '16 at 13:06









                                                      melvinvmelvinv

                                                      1165




                                                      1165























                                                          2














                                                          Using Express Middleware works great for me. If you are already using Express, just add the following middleware rules. It should start working.



                                                          app.all("/api/*", function(req, res, next) {
                                                          res.header("Access-Control-Allow-Origin", "*");
                                                          res.header("Access-Control-Allow-Headers", "Cache-Control, Pragma, Origin, Authorization, Content-Type, X-Requested-With");
                                                          res.header("Access-Control-Allow-Methods", "GET, PUT, POST");
                                                          return next();
                                                          });

                                                          app.all("/api/*", function(req, res, next) {
                                                          if (req.method.toLowerCase() !== "options") {
                                                          return next();
                                                          }
                                                          return res.send(204);
                                                          });


                                                          Reference






                                                          share|improve this answer




























                                                            2














                                                            Using Express Middleware works great for me. If you are already using Express, just add the following middleware rules. It should start working.



                                                            app.all("/api/*", function(req, res, next) {
                                                            res.header("Access-Control-Allow-Origin", "*");
                                                            res.header("Access-Control-Allow-Headers", "Cache-Control, Pragma, Origin, Authorization, Content-Type, X-Requested-With");
                                                            res.header("Access-Control-Allow-Methods", "GET, PUT, POST");
                                                            return next();
                                                            });

                                                            app.all("/api/*", function(req, res, next) {
                                                            if (req.method.toLowerCase() !== "options") {
                                                            return next();
                                                            }
                                                            return res.send(204);
                                                            });


                                                            Reference






                                                            share|improve this answer


























                                                              2












                                                              2








                                                              2







                                                              Using Express Middleware works great for me. If you are already using Express, just add the following middleware rules. It should start working.



                                                              app.all("/api/*", function(req, res, next) {
                                                              res.header("Access-Control-Allow-Origin", "*");
                                                              res.header("Access-Control-Allow-Headers", "Cache-Control, Pragma, Origin, Authorization, Content-Type, X-Requested-With");
                                                              res.header("Access-Control-Allow-Methods", "GET, PUT, POST");
                                                              return next();
                                                              });

                                                              app.all("/api/*", function(req, res, next) {
                                                              if (req.method.toLowerCase() !== "options") {
                                                              return next();
                                                              }
                                                              return res.send(204);
                                                              });


                                                              Reference






                                                              share|improve this answer













                                                              Using Express Middleware works great for me. If you are already using Express, just add the following middleware rules. It should start working.



                                                              app.all("/api/*", function(req, res, next) {
                                                              res.header("Access-Control-Allow-Origin", "*");
                                                              res.header("Access-Control-Allow-Headers", "Cache-Control, Pragma, Origin, Authorization, Content-Type, X-Requested-With");
                                                              res.header("Access-Control-Allow-Methods", "GET, PUT, POST");
                                                              return next();
                                                              });

                                                              app.all("/api/*", function(req, res, next) {
                                                              if (req.method.toLowerCase() !== "options") {
                                                              return next();
                                                              }
                                                              return res.send(204);
                                                              });


                                                              Reference







                                                              share|improve this answer












                                                              share|improve this answer



                                                              share|improve this answer










                                                              answered Aug 29 '18 at 18:29









                                                              Ishan PatelIshan Patel

                                                              4631621




                                                              4631621























                                                                  1














                                                                  We can avoid CORS and forward the requests to the other server instead:



                                                                  // config:
                                                                  var public_folder = __dirname + '/public'
                                                                  var apiServerHost = 'http://other.server'

                                                                  // code:
                                                                  console.log("starting server...");

                                                                  var express = require('express');
                                                                  var app = express();
                                                                  var request = require('request');

                                                                  // serve static files
                                                                  app.use(express.static(public_folder));

                                                                  // if not found, serve from another server
                                                                  app.use(function(req, res) {
                                                                  var url = apiServerHost + req.url;
                                                                  req.pipe(request(url)).pipe(res);
                                                                  });

                                                                  app.listen(80, function(){
                                                                  console.log("server ready");
                                                                  });





                                                                  share|improve this answer


























                                                                  • this does not answer the question asked

                                                                    – david.barkhuizen
                                                                    Jan 16 '18 at 12:53
















                                                                  1














                                                                  We can avoid CORS and forward the requests to the other server instead:



                                                                  // config:
                                                                  var public_folder = __dirname + '/public'
                                                                  var apiServerHost = 'http://other.server'

                                                                  // code:
                                                                  console.log("starting server...");

                                                                  var express = require('express');
                                                                  var app = express();
                                                                  var request = require('request');

                                                                  // serve static files
                                                                  app.use(express.static(public_folder));

                                                                  // if not found, serve from another server
                                                                  app.use(function(req, res) {
                                                                  var url = apiServerHost + req.url;
                                                                  req.pipe(request(url)).pipe(res);
                                                                  });

                                                                  app.listen(80, function(){
                                                                  console.log("server ready");
                                                                  });





                                                                  share|improve this answer


























                                                                  • this does not answer the question asked

                                                                    – david.barkhuizen
                                                                    Jan 16 '18 at 12:53














                                                                  1












                                                                  1








                                                                  1







                                                                  We can avoid CORS and forward the requests to the other server instead:



                                                                  // config:
                                                                  var public_folder = __dirname + '/public'
                                                                  var apiServerHost = 'http://other.server'

                                                                  // code:
                                                                  console.log("starting server...");

                                                                  var express = require('express');
                                                                  var app = express();
                                                                  var request = require('request');

                                                                  // serve static files
                                                                  app.use(express.static(public_folder));

                                                                  // if not found, serve from another server
                                                                  app.use(function(req, res) {
                                                                  var url = apiServerHost + req.url;
                                                                  req.pipe(request(url)).pipe(res);
                                                                  });

                                                                  app.listen(80, function(){
                                                                  console.log("server ready");
                                                                  });





                                                                  share|improve this answer















                                                                  We can avoid CORS and forward the requests to the other server instead:



                                                                  // config:
                                                                  var public_folder = __dirname + '/public'
                                                                  var apiServerHost = 'http://other.server'

                                                                  // code:
                                                                  console.log("starting server...");

                                                                  var express = require('express');
                                                                  var app = express();
                                                                  var request = require('request');

                                                                  // serve static files
                                                                  app.use(express.static(public_folder));

                                                                  // if not found, serve from another server
                                                                  app.use(function(req, res) {
                                                                  var url = apiServerHost + req.url;
                                                                  req.pipe(request(url)).pipe(res);
                                                                  });

                                                                  app.listen(80, function(){
                                                                  console.log("server ready");
                                                                  });






                                                                  share|improve this answer














                                                                  share|improve this answer



                                                                  share|improve this answer








                                                                  edited May 15 '16 at 8:53

























                                                                  answered May 15 '16 at 8:45









                                                                  Bernardo RamosBernardo Ramos

                                                                  1,5481517




                                                                  1,5481517













                                                                  • this does not answer the question asked

                                                                    – david.barkhuizen
                                                                    Jan 16 '18 at 12:53



















                                                                  • this does not answer the question asked

                                                                    – david.barkhuizen
                                                                    Jan 16 '18 at 12:53

















                                                                  this does not answer the question asked

                                                                  – david.barkhuizen
                                                                  Jan 16 '18 at 12:53





                                                                  this does not answer the question asked

                                                                  – david.barkhuizen
                                                                  Jan 16 '18 at 12:53











                                                                  1














                                                                  I used the following steps to my web app and I had success:



                                                                  Add the cors package to the express:



                                                                  npm install cors --save


                                                                  Add following lines after the bodyParser configuration. I had some troubles adding before bodyParser:



                                                                   // enable cors to the server
                                                                  const corsOpt = {
                                                                  origin: process.env.CORS_ALLOW_ORIGIN || '*', // this work well to configure origin url in the server
                                                                  methods: ['GET', 'PUT', 'POST', 'DELETE', 'OPTIONS'], // to works well with web app, OPTIONS is required
                                                                  allowedHeaders: ['Content-Type', 'Authorization'] // allow json and token in the headers
                                                                  };
                                                                  app.use(cors(corsOpt)); // cors for all the routes of the application
                                                                  app.options('*', cors(corsOpt)); // automatic cors gen for HTTP verbs in all routes, This can be redundant but I kept to be sure that will always work.





                                                                  share|improve this answer




























                                                                    1














                                                                    I used the following steps to my web app and I had success:



                                                                    Add the cors package to the express:



                                                                    npm install cors --save


                                                                    Add following lines after the bodyParser configuration. I had some troubles adding before bodyParser:



                                                                     // enable cors to the server
                                                                    const corsOpt = {
                                                                    origin: process.env.CORS_ALLOW_ORIGIN || '*', // this work well to configure origin url in the server
                                                                    methods: ['GET', 'PUT', 'POST', 'DELETE', 'OPTIONS'], // to works well with web app, OPTIONS is required
                                                                    allowedHeaders: ['Content-Type', 'Authorization'] // allow json and token in the headers
                                                                    };
                                                                    app.use(cors(corsOpt)); // cors for all the routes of the application
                                                                    app.options('*', cors(corsOpt)); // automatic cors gen for HTTP verbs in all routes, This can be redundant but I kept to be sure that will always work.





                                                                    share|improve this answer


























                                                                      1












                                                                      1








                                                                      1







                                                                      I used the following steps to my web app and I had success:



                                                                      Add the cors package to the express:



                                                                      npm install cors --save


                                                                      Add following lines after the bodyParser configuration. I had some troubles adding before bodyParser:



                                                                       // enable cors to the server
                                                                      const corsOpt = {
                                                                      origin: process.env.CORS_ALLOW_ORIGIN || '*', // this work well to configure origin url in the server
                                                                      methods: ['GET', 'PUT', 'POST', 'DELETE', 'OPTIONS'], // to works well with web app, OPTIONS is required
                                                                      allowedHeaders: ['Content-Type', 'Authorization'] // allow json and token in the headers
                                                                      };
                                                                      app.use(cors(corsOpt)); // cors for all the routes of the application
                                                                      app.options('*', cors(corsOpt)); // automatic cors gen for HTTP verbs in all routes, This can be redundant but I kept to be sure that will always work.





                                                                      share|improve this answer













                                                                      I used the following steps to my web app and I had success:



                                                                      Add the cors package to the express:



                                                                      npm install cors --save


                                                                      Add following lines after the bodyParser configuration. I had some troubles adding before bodyParser:



                                                                       // enable cors to the server
                                                                      const corsOpt = {
                                                                      origin: process.env.CORS_ALLOW_ORIGIN || '*', // this work well to configure origin url in the server
                                                                      methods: ['GET', 'PUT', 'POST', 'DELETE', 'OPTIONS'], // to works well with web app, OPTIONS is required
                                                                      allowedHeaders: ['Content-Type', 'Authorization'] // allow json and token in the headers
                                                                      };
                                                                      app.use(cors(corsOpt)); // cors for all the routes of the application
                                                                      app.options('*', cors(corsOpt)); // automatic cors gen for HTTP verbs in all routes, This can be redundant but I kept to be sure that will always work.






                                                                      share|improve this answer












                                                                      share|improve this answer



                                                                      share|improve this answer










                                                                      answered Jun 14 '18 at 13:36









                                                                      Ângelo PolottoÂngelo Polotto

                                                                      48767




                                                                      48767























                                                                          0














                                                                          This is similiar to Pat's answer with the difference that I finish with res.sendStatus(200); instead of next();



                                                                          The code will catch all the requests of the method type OPTIONS and send back access-control-headers.



                                                                          app.options('/*', (req, res, next) => {
                                                                          res.header('Access-Control-Allow-Origin', '*');
                                                                          res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
                                                                          res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');
                                                                          res.sendStatus(200);
                                                                          });


                                                                          The code accepts CORS from all origins as requested in the question. However, it would be better to replace the * with a specific origin i.e. http://localhost:8080 to prevent misuse.



                                                                          Since we use the app.options-method instead of the app.use-method we don't need to make this check:



                                                                          req.method === 'OPTIONS'


                                                                          which we can see in some of the other answers.



                                                                          I found the answer here: http://johnzhang.io/options-request-in-express.






                                                                          share|improve this answer






























                                                                            0














                                                                            This is similiar to Pat's answer with the difference that I finish with res.sendStatus(200); instead of next();



                                                                            The code will catch all the requests of the method type OPTIONS and send back access-control-headers.



                                                                            app.options('/*', (req, res, next) => {
                                                                            res.header('Access-Control-Allow-Origin', '*');
                                                                            res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
                                                                            res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');
                                                                            res.sendStatus(200);
                                                                            });


                                                                            The code accepts CORS from all origins as requested in the question. However, it would be better to replace the * with a specific origin i.e. http://localhost:8080 to prevent misuse.



                                                                            Since we use the app.options-method instead of the app.use-method we don't need to make this check:



                                                                            req.method === 'OPTIONS'


                                                                            which we can see in some of the other answers.



                                                                            I found the answer here: http://johnzhang.io/options-request-in-express.






                                                                            share|improve this answer




























                                                                              0












                                                                              0








                                                                              0







                                                                              This is similiar to Pat's answer with the difference that I finish with res.sendStatus(200); instead of next();



                                                                              The code will catch all the requests of the method type OPTIONS and send back access-control-headers.



                                                                              app.options('/*', (req, res, next) => {
                                                                              res.header('Access-Control-Allow-Origin', '*');
                                                                              res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
                                                                              res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');
                                                                              res.sendStatus(200);
                                                                              });


                                                                              The code accepts CORS from all origins as requested in the question. However, it would be better to replace the * with a specific origin i.e. http://localhost:8080 to prevent misuse.



                                                                              Since we use the app.options-method instead of the app.use-method we don't need to make this check:



                                                                              req.method === 'OPTIONS'


                                                                              which we can see in some of the other answers.



                                                                              I found the answer here: http://johnzhang.io/options-request-in-express.






                                                                              share|improve this answer















                                                                              This is similiar to Pat's answer with the difference that I finish with res.sendStatus(200); instead of next();



                                                                              The code will catch all the requests of the method type OPTIONS and send back access-control-headers.



                                                                              app.options('/*', (req, res, next) => {
                                                                              res.header('Access-Control-Allow-Origin', '*');
                                                                              res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
                                                                              res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');
                                                                              res.sendStatus(200);
                                                                              });


                                                                              The code accepts CORS from all origins as requested in the question. However, it would be better to replace the * with a specific origin i.e. http://localhost:8080 to prevent misuse.



                                                                              Since we use the app.options-method instead of the app.use-method we don't need to make this check:



                                                                              req.method === 'OPTIONS'


                                                                              which we can see in some of the other answers.



                                                                              I found the answer here: http://johnzhang.io/options-request-in-express.







                                                                              share|improve this answer














                                                                              share|improve this answer



                                                                              share|improve this answer








                                                                              edited 2 days ago

























                                                                              answered 2 days ago









                                                                              SwootSwoot

                                                                              56648




                                                                              56648























                                                                                  -1














                                                                                  In typescript, if you want to use the node.js package cors



                                                                                  /**
                                                                                  * app.ts
                                                                                  * If you use the cors library
                                                                                  */

                                                                                  import * as express from "express";
                                                                                  [...]
                                                                                  import * as cors from 'cors';

                                                                                  class App {
                                                                                  public express: express.Application;

                                                                                  constructor() {
                                                                                  this.express = express();
                                                                                  [..]
                                                                                  this.handleCORSErrors();
                                                                                  }

                                                                                  private handleCORSErrors(): any {
                                                                                  const corsOptions: cors.CorsOptions = {
                                                                                  origin: 'http://example.com',
                                                                                  optionsSuccessStatus: 200
                                                                                  };
                                                                                  this.express.use(cors(corsOptions));
                                                                                  }
                                                                                  }

                                                                                  export default new App().express;


                                                                                  If you don't want to use third part libraries for cors error handling, you need to change the handleCORSErrors() method.



                                                                                  /**
                                                                                  * app.ts
                                                                                  * If you do not use the cors library
                                                                                  */

                                                                                  import * as express from "express";
                                                                                  [...]

                                                                                  class App {
                                                                                  public express: express.Application;

                                                                                  constructor() {
                                                                                  this.express = express();
                                                                                  [..]
                                                                                  this.handleCORSErrors();
                                                                                  }

                                                                                  private handleCORSErrors(): any {
                                                                                  this.express.use((req, res, next) => {
                                                                                  res.header("Access-Control-Allow-Origin", "*");
                                                                                  res.header(
                                                                                  "Access-Control-ALlow-Headers",
                                                                                  "Origin, X-Requested-With, Content-Type, Accept, Authorization"
                                                                                  );
                                                                                  if (req.method === "OPTIONS") {
                                                                                  res.header(
                                                                                  "Access-Control-Allow-Methods",
                                                                                  "PUT, POST, PATCH, GET, DELETE"
                                                                                  );
                                                                                  return res.status(200).json({});
                                                                                  }
                                                                                  next(); // send the request to the next middleware
                                                                                  });
                                                                                  }
                                                                                  }

                                                                                  export default new App().express;


                                                                                  For using the app.ts file



                                                                                  /**
                                                                                  * server.ts
                                                                                  */
                                                                                  import * as http from "http";
                                                                                  import app from "./app";

                                                                                  const server: http.Server = http.createServer(app);

                                                                                  const PORT: any = process.env.PORT || 3000;
                                                                                  server.listen(PORT);





                                                                                  share|improve this answer





















                                                                                  • 1





                                                                                    "If the server is written in typescript" — It isn't. The question says it is written in CoffeeScript.

                                                                                    – Quentin
                                                                                    Jul 9 '18 at 9:44






                                                                                  • 1





                                                                                    @Quentin I just wanted to show an alternative in typesript, hoping that this could help somebody.

                                                                                    – overcomer
                                                                                    Jul 9 '18 at 9:49
















                                                                                  -1














                                                                                  In typescript, if you want to use the node.js package cors



                                                                                  /**
                                                                                  * app.ts
                                                                                  * If you use the cors library
                                                                                  */

                                                                                  import * as express from "express";
                                                                                  [...]
                                                                                  import * as cors from 'cors';

                                                                                  class App {
                                                                                  public express: express.Application;

                                                                                  constructor() {
                                                                                  this.express = express();
                                                                                  [..]
                                                                                  this.handleCORSErrors();
                                                                                  }

                                                                                  private handleCORSErrors(): any {
                                                                                  const corsOptions: cors.CorsOptions = {
                                                                                  origin: 'http://example.com',
                                                                                  optionsSuccessStatus: 200
                                                                                  };
                                                                                  this.express.use(cors(corsOptions));
                                                                                  }
                                                                                  }

                                                                                  export default new App().express;


                                                                                  If you don't want to use third part libraries for cors error handling, you need to change the handleCORSErrors() method.



                                                                                  /**
                                                                                  * app.ts
                                                                                  * If you do not use the cors library
                                                                                  */

                                                                                  import * as express from "express";
                                                                                  [...]

                                                                                  class App {
                                                                                  public express: express.Application;

                                                                                  constructor() {
                                                                                  this.express = express();
                                                                                  [..]
                                                                                  this.handleCORSErrors();
                                                                                  }

                                                                                  private handleCORSErrors(): any {
                                                                                  this.express.use((req, res, next) => {
                                                                                  res.header("Access-Control-Allow-Origin", "*");
                                                                                  res.header(
                                                                                  "Access-Control-ALlow-Headers",
                                                                                  "Origin, X-Requested-With, Content-Type, Accept, Authorization"
                                                                                  );
                                                                                  if (req.method === "OPTIONS") {
                                                                                  res.header(
                                                                                  "Access-Control-Allow-Methods",
                                                                                  "PUT, POST, PATCH, GET, DELETE"
                                                                                  );
                                                                                  return res.status(200).json({});
                                                                                  }
                                                                                  next(); // send the request to the next middleware
                                                                                  });
                                                                                  }
                                                                                  }

                                                                                  export default new App().express;


                                                                                  For using the app.ts file



                                                                                  /**
                                                                                  * server.ts
                                                                                  */
                                                                                  import * as http from "http";
                                                                                  import app from "./app";

                                                                                  const server: http.Server = http.createServer(app);

                                                                                  const PORT: any = process.env.PORT || 3000;
                                                                                  server.listen(PORT);





                                                                                  share|improve this answer





















                                                                                  • 1





                                                                                    "If the server is written in typescript" — It isn't. The question says it is written in CoffeeScript.

                                                                                    – Quentin
                                                                                    Jul 9 '18 at 9:44






                                                                                  • 1





                                                                                    @Quentin I just wanted to show an alternative in typesript, hoping that this could help somebody.

                                                                                    – overcomer
                                                                                    Jul 9 '18 at 9:49














                                                                                  -1












                                                                                  -1








                                                                                  -1







                                                                                  In typescript, if you want to use the node.js package cors



                                                                                  /**
                                                                                  * app.ts
                                                                                  * If you use the cors library
                                                                                  */

                                                                                  import * as express from "express";
                                                                                  [...]
                                                                                  import * as cors from 'cors';

                                                                                  class App {
                                                                                  public express: express.Application;

                                                                                  constructor() {
                                                                                  this.express = express();
                                                                                  [..]
                                                                                  this.handleCORSErrors();
                                                                                  }

                                                                                  private handleCORSErrors(): any {
                                                                                  const corsOptions: cors.CorsOptions = {
                                                                                  origin: 'http://example.com',
                                                                                  optionsSuccessStatus: 200
                                                                                  };
                                                                                  this.express.use(cors(corsOptions));
                                                                                  }
                                                                                  }

                                                                                  export default new App().express;


                                                                                  If you don't want to use third part libraries for cors error handling, you need to change the handleCORSErrors() method.



                                                                                  /**
                                                                                  * app.ts
                                                                                  * If you do not use the cors library
                                                                                  */

                                                                                  import * as express from "express";
                                                                                  [...]

                                                                                  class App {
                                                                                  public express: express.Application;

                                                                                  constructor() {
                                                                                  this.express = express();
                                                                                  [..]
                                                                                  this.handleCORSErrors();
                                                                                  }

                                                                                  private handleCORSErrors(): any {
                                                                                  this.express.use((req, res, next) => {
                                                                                  res.header("Access-Control-Allow-Origin", "*");
                                                                                  res.header(
                                                                                  "Access-Control-ALlow-Headers",
                                                                                  "Origin, X-Requested-With, Content-Type, Accept, Authorization"
                                                                                  );
                                                                                  if (req.method === "OPTIONS") {
                                                                                  res.header(
                                                                                  "Access-Control-Allow-Methods",
                                                                                  "PUT, POST, PATCH, GET, DELETE"
                                                                                  );
                                                                                  return res.status(200).json({});
                                                                                  }
                                                                                  next(); // send the request to the next middleware
                                                                                  });
                                                                                  }
                                                                                  }

                                                                                  export default new App().express;


                                                                                  For using the app.ts file



                                                                                  /**
                                                                                  * server.ts
                                                                                  */
                                                                                  import * as http from "http";
                                                                                  import app from "./app";

                                                                                  const server: http.Server = http.createServer(app);

                                                                                  const PORT: any = process.env.PORT || 3000;
                                                                                  server.listen(PORT);





                                                                                  share|improve this answer















                                                                                  In typescript, if you want to use the node.js package cors



                                                                                  /**
                                                                                  * app.ts
                                                                                  * If you use the cors library
                                                                                  */

                                                                                  import * as express from "express";
                                                                                  [...]
                                                                                  import * as cors from 'cors';

                                                                                  class App {
                                                                                  public express: express.Application;

                                                                                  constructor() {
                                                                                  this.express = express();
                                                                                  [..]
                                                                                  this.handleCORSErrors();
                                                                                  }

                                                                                  private handleCORSErrors(): any {
                                                                                  const corsOptions: cors.CorsOptions = {
                                                                                  origin: 'http://example.com',
                                                                                  optionsSuccessStatus: 200
                                                                                  };
                                                                                  this.express.use(cors(corsOptions));
                                                                                  }
                                                                                  }

                                                                                  export default new App().express;


                                                                                  If you don't want to use third part libraries for cors error handling, you need to change the handleCORSErrors() method.



                                                                                  /**
                                                                                  * app.ts
                                                                                  * If you do not use the cors library
                                                                                  */

                                                                                  import * as express from "express";
                                                                                  [...]

                                                                                  class App {
                                                                                  public express: express.Application;

                                                                                  constructor() {
                                                                                  this.express = express();
                                                                                  [..]
                                                                                  this.handleCORSErrors();
                                                                                  }

                                                                                  private handleCORSErrors(): any {
                                                                                  this.express.use((req, res, next) => {
                                                                                  res.header("Access-Control-Allow-Origin", "*");
                                                                                  res.header(
                                                                                  "Access-Control-ALlow-Headers",
                                                                                  "Origin, X-Requested-With, Content-Type, Accept, Authorization"
                                                                                  );
                                                                                  if (req.method === "OPTIONS") {
                                                                                  res.header(
                                                                                  "Access-Control-Allow-Methods",
                                                                                  "PUT, POST, PATCH, GET, DELETE"
                                                                                  );
                                                                                  return res.status(200).json({});
                                                                                  }
                                                                                  next(); // send the request to the next middleware
                                                                                  });
                                                                                  }
                                                                                  }

                                                                                  export default new App().express;


                                                                                  For using the app.ts file



                                                                                  /**
                                                                                  * server.ts
                                                                                  */
                                                                                  import * as http from "http";
                                                                                  import app from "./app";

                                                                                  const server: http.Server = http.createServer(app);

                                                                                  const PORT: any = process.env.PORT || 3000;
                                                                                  server.listen(PORT);






                                                                                  share|improve this answer














                                                                                  share|improve this answer



                                                                                  share|improve this answer








                                                                                  edited Jul 9 '18 at 10:10

























                                                                                  answered Jul 9 '18 at 9:41









                                                                                  overcomerovercomer

                                                                                  5141824




                                                                                  5141824








                                                                                  • 1





                                                                                    "If the server is written in typescript" — It isn't. The question says it is written in CoffeeScript.

                                                                                    – Quentin
                                                                                    Jul 9 '18 at 9:44






                                                                                  • 1





                                                                                    @Quentin I just wanted to show an alternative in typesript, hoping that this could help somebody.

                                                                                    – overcomer
                                                                                    Jul 9 '18 at 9:49














                                                                                  • 1





                                                                                    "If the server is written in typescript" — It isn't. The question says it is written in CoffeeScript.

                                                                                    – Quentin
                                                                                    Jul 9 '18 at 9:44






                                                                                  • 1





                                                                                    @Quentin I just wanted to show an alternative in typesript, hoping that this could help somebody.

                                                                                    – overcomer
                                                                                    Jul 9 '18 at 9:49








                                                                                  1




                                                                                  1





                                                                                  "If the server is written in typescript" — It isn't. The question says it is written in CoffeeScript.

                                                                                  – Quentin
                                                                                  Jul 9 '18 at 9:44





                                                                                  "If the server is written in typescript" — It isn't. The question says it is written in CoffeeScript.

                                                                                  – Quentin
                                                                                  Jul 9 '18 at 9:44




                                                                                  1




                                                                                  1





                                                                                  @Quentin I just wanted to show an alternative in typesript, hoping that this could help somebody.

                                                                                  – overcomer
                                                                                  Jul 9 '18 at 9:49





                                                                                  @Quentin I just wanted to show an alternative in typesript, hoping that this could help somebody.

                                                                                  – overcomer
                                                                                  Jul 9 '18 at 9:49











                                                                                  -1














                                                                                  Below code will work ,but first install cors by:



                                                                                  npm install --save cors



                                                                                  Then:



                                                                                  module.exports = function(app) { 
                                                                                  var express = require("express");
                                                                                  var cors = require('cors');
                                                                                  var router = express.Router();
                                                                                  app.use(cors());

                                                                                  app.post("/movies",cors(), function(req, res) {
                                                                                  res.send("test");
                                                                                  });





                                                                                  share|improve this answer





















                                                                                  • 2





                                                                                    Duplicate answer. There are already answers like this here.

                                                                                    – Maihan Nijat
                                                                                    Oct 17 '18 at 16:03
















                                                                                  -1














                                                                                  Below code will work ,but first install cors by:



                                                                                  npm install --save cors



                                                                                  Then:



                                                                                  module.exports = function(app) { 
                                                                                  var express = require("express");
                                                                                  var cors = require('cors');
                                                                                  var router = express.Router();
                                                                                  app.use(cors());

                                                                                  app.post("/movies",cors(), function(req, res) {
                                                                                  res.send("test");
                                                                                  });





                                                                                  share|improve this answer





















                                                                                  • 2





                                                                                    Duplicate answer. There are already answers like this here.

                                                                                    – Maihan Nijat
                                                                                    Oct 17 '18 at 16:03














                                                                                  -1












                                                                                  -1








                                                                                  -1







                                                                                  Below code will work ,but first install cors by:



                                                                                  npm install --save cors



                                                                                  Then:



                                                                                  module.exports = function(app) { 
                                                                                  var express = require("express");
                                                                                  var cors = require('cors');
                                                                                  var router = express.Router();
                                                                                  app.use(cors());

                                                                                  app.post("/movies",cors(), function(req, res) {
                                                                                  res.send("test");
                                                                                  });





                                                                                  share|improve this answer















                                                                                  Below code will work ,but first install cors by:



                                                                                  npm install --save cors



                                                                                  Then:



                                                                                  module.exports = function(app) { 
                                                                                  var express = require("express");
                                                                                  var cors = require('cors');
                                                                                  var router = express.Router();
                                                                                  app.use(cors());

                                                                                  app.post("/movies",cors(), function(req, res) {
                                                                                  res.send("test");
                                                                                  });






                                                                                  share|improve this answer














                                                                                  share|improve this answer



                                                                                  share|improve this answer








                                                                                  edited Oct 2 '18 at 13:54

























                                                                                  answered Oct 2 '18 at 13:40









                                                                                  BCoolBCool

                                                                                  174




                                                                                  174








                                                                                  • 2





                                                                                    Duplicate answer. There are already answers like this here.

                                                                                    – Maihan Nijat
                                                                                    Oct 17 '18 at 16:03














                                                                                  • 2





                                                                                    Duplicate answer. There are already answers like this here.

                                                                                    – Maihan Nijat
                                                                                    Oct 17 '18 at 16:03








                                                                                  2




                                                                                  2





                                                                                  Duplicate answer. There are already answers like this here.

                                                                                  – Maihan Nijat
                                                                                  Oct 17 '18 at 16:03





                                                                                  Duplicate answer. There are already answers like this here.

                                                                                  – Maihan Nijat
                                                                                  Oct 17 '18 at 16:03





                                                                                  protected by Community Oct 27 '17 at 8:04



                                                                                  Thank you for your interest in this question.
                                                                                  Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).



                                                                                  Would you like to answer one of these unanswered questions instead?



                                                                                  Popular posts from this blog

                                                                                  Full-time equivalent

                                                                                  Bicuculline

                                                                                  さくらももこ