How to enable cors nodejs with express?

前端 未结 6 1087
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-29 07:04

In summary I am using a viewer like api of dicom files called cornerstone, for this I connect to the WADO service of dc4chee to get the dicom, dcm4chee runs port 8080, and m

相关标签:
6条回答
  • 2020-11-29 07:23

    To enable cors you can do this:

    var cors = require('cors');
    app.use(cors());
    // to change your ports for different cors stuff:
    app.set('port', process.env.PORT || 3000);
    app.listen(app.get('port'), function() { 
      console.log('we are listening on: ', 
      app.get('port'))
    });
    

    Remember that cors are middleware, so you will want to have app.use before it so that your incoming requests will go through cors before they hit your routes.

    You can change the ports depending on which one you want to use. I am pretty sure you can also replace the || with && to listen on multiple ports and set cors on those.

    In raw node, I believe you have to use the writeHead, but I am not sure about the raw node implementation.

    0 讨论(0)
  • 2020-11-29 07:25

    The error displayed by the browser means, server localhost:8080 refused a request from localhost:3000, It seems cors didn't set well on server localhost:8080.

    The response header should have something like this:

    Access-Control-Allow-Headers:Content-Type,Content-Length, Authorization, Accept,X-Requested-With
    Access-Control-Allow-Methods:PUT,POST,GET,DELETE,OPTIONS
    Access-Control-Allow-Origin:*
    

    Try add cors header in your 8080 server.

    app.all('*', function (req, res) {
        res.header("Access-Control-Allow-Origin", "*");
      res.header("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");
      res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    //...
    
    0 讨论(0)
  • 2020-11-29 07:26

    do

    npm install cors --save
    

    and just add these lines in your main file where your request is going.

    const cors = require('cors');
    const express = require('express');
    let app = express();
    app.use(cors());
    app.options('*', cors());
    
    0 讨论(0)
  • 2020-11-29 07:26
    //Définition des CORS Middleware 
    app.use(function(req, res, next) {
        res.setHeader("Access-Control-Allow-Headers", "X-Requested-With,content-type, Accept,Authorization,Origin");
        res.setHeader("Access-Control-Allow-Origin", "*");
        res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, PATCH, DELETE");
        res.setHeader("Access-Control-Allow-Credentials", true);
        next();
      });`enter code here`
    
    0 讨论(0)
  • 2020-11-29 07:34

    Adding CORS(Cross-Origin-Resource-Sharing) to your node, express app is quite easy...

    You need to install cors library via npm first, using the command below:

    npm install cors -S
    

    and if you need it globally, just add -g flag to it...

    Then in your express app, do this:

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

    Also these are other examples for cors from their doc:

    var express = require('express')
    var cors = require('cors')
    var app = express()
    
    app.use(cors())
    
    app.get('/products/:id', function (req, res, next) {
      res.json({msg: 'This is CORS-enabled for all origins!'})
    })
    
    app.listen(80, function () {
      console.log('CORS-enabled web server listening on port 80')
    })
    

    Configuring CORS Asynchronously:

    var express = require('express')
    var cors = require('cors')
    var app = express()
    
    var whitelist = ['http://example1.com', 'http://example2.com']
    var corsOptionsDelegate = function (req, callback) {
      var corsOptions;
      if (whitelist.indexOf(req.header('Origin')) !== -1) {
        corsOptions = { origin: true } // reflect (enable) the requested origin in the CORS response
      }else{
        corsOptions = { origin: false } // disable CORS for this request
      }
      callback(null, corsOptions) // callback expects two parameters: error and options
    }
    
    app.get('/products/:id', cors(corsOptionsDelegate), function (req, res, next) {
      res.json({msg: 'This is CORS-enabled for a whitelisted domain.'})
    })
    
    app.listen(80, function () {
      console.log('CORS-enabled web server listening on port 80')
    })
    
    0 讨论(0)
  • 2020-11-29 07:36

    This code is helped me to resolve the resources cors issue with the express. And You can use other options easily with the asynchronous origin configuration.

    var cors = require('cors'); //import cors module
    
    var whitelist = ['http://localhost:8000', 'http://localhost:8080']; //white list consumers
    var corsOptions = {
      origin: function (origin, callback) {
        if (whitelist.indexOf(origin) !== -1) {
          callback(null, true);
        } else {
          callback(null, false);
        }
      },
      methods: ['GET', 'PUT', 'POST', 'DELETE', 'OPTIONS'],
      optionsSuccessStatus: 200, // some legacy browsers (IE11, various SmartTVs) choke on 204
      credentials: true, //Credentials are cookies, authorization headers or TLS client certificates.
      allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With', 'device-remember-token', 'Access-Control-Allow-Origin', 'Origin', 'Accept']
    };
    
    app.use(cors(corsOptions)); //adding cors middleware to the express with above configurations
    
    0 讨论(0)
提交回复
热议问题