yandex
loader

please wait

  • Shreya Bansal Feb-15-2019 07:42:37 AM ( 3 months ago )

    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?

  • Jadav Payeng Feb-15-2019 07:44:53 AM ( 3 months ago )

    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

  • Shiv Thapa Feb-15-2019 07:47:10 AM ( 3 months ago )

    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.

  • Jignesh Patel Feb-15-2019 07:48:25 AM ( 3 months ago )

    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'));
    });

     
  • Naveen Shastri Feb-15-2019 07:55:02 AM ( 3 months ago )

    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

     
  • Vanshika Bhatt Feb-15-2019 07:56:02 AM ( 3 months ago )

    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());
     
  • Pooja Bhardwaj Feb-15-2019 07:58:01 AM ( 3 months ago )

    I have made a more complete middleware suitable for express or connect. It supports OPTIONSrequests 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();
        }
    });
     
  • Shalini Jaiswal Feb-15-2019 07:59:09 AM ( 3 months ago )

    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

     
  • Atul Kasana Feb-15-2019 08:01:00 AM ( 3 months ago )

    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();
    });
  • Priya Roy Feb-15-2019 08:01:45 AM ( 3 months ago )

    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();
    });
     

Please login

Similar Discussion

Recommended For You