How to enable cors nodejs with express?

前端 未结 6 1088
佛祖请我去吃肉
佛祖请我去吃肉 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: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')
    })
    

提交回复
热议问题