如何使用express启用cors nodejs?

时间:2017-03-31 21:37:37

标签: javascript node.js express cors dicom

总而言之,我使用的是像dicom文件api这样的浏览器,称为基石,为此我连接到dc4chee的WADO服务以获取dicom,dcm4chee运行端口8080,我的节点上的应用程序使用端口3000,所以我是试图显示浏览器的dicom。

https://www.npmjs.com/package/cornerstone-wado-image-loader

这是浏览器显示的错误

XMLHttpRequest can not load http: // localhost: 8080 / wado? RequestType = WADO & studyUID = 1.2.840.113704.1.111.5 ... 26513.429 & contentType = application% 2Fdicom & transferSyntax = 1.2.840.10008.1.2. In 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http: // localhost: 3000' is therefore not allowed access.

在指定的文档中

请注意,Web服务器必须支持跨源资源共享,否则图像将无法加载。如果您无法在Web服务器上启用CORS,而您正在加载DICOM P10实例,则可以使用反向代理。这是一个基于http-proxy的简单Node.js,它添加​​了你可能会觉得有用的CORS头文件。

并显示此示例代码但我正在使用express并且此代码不起作用

Var http = require ('http'),
    HttpProxy = require ('http-proxy');

Var proxy = httpProxy.createProxyServer ({target: 'http: // localhost: 8042'}) .listen (8000);

Proxy.on ('proxyRes', function (proxyReq, req, res, options) {
  // add the CORS header to the response
  Res.setHeader ('Access-Control-Allow-Origin', '*');
});

Proxy.on ('error', function (e) {
  // suppress errors
});

此处还使用npm cors代码

Var express = require ('express')
Var cors = require ('cors')
Var app = express ()
 
App.get ('/ products /: id', cors (), function (req, res, next) {
  Res.json ({msg: 'This is CORS-enabled for a Single Route'))
})
 
App.listen (80, function () {
  Console.log ('CORS-enabled web server listening on port 80')
})

但有了这个,我在端口3000而不是8080上启用了cors,我需要激活模式或在标头响应中添加'Access-Control-Allow-Origin而不是在标头请求中

如何在端口8080上添加CORS,其中dcm4chee从NODEjs运行?

抱歉我的英文

更新!

服务器响应以下内容;

RESPONDE HEADER

Content-Type:application/dicom
Date:Sat, 01 Apr 2017 01:15:38 GMT
Expires:0
Server:Apache-Coyote/1.1
Transfer-Encoding:chunked
X-Powered-By:Servlet 2.4; JBoss-4.2.3.GA (build: SVNTag=JBoss_4_2_3_GA 
date=200807181439)/JBossWeb-2.0

请求标题

Accept:*/*
Accept-Encoding:gzip, deflate, sdch, br
Accept-Language:es-ES,es;q=0.8,en-US;q=0.6,en;q=0.4
Connection:keep-alive
Host:localhost:8080
Origin:http: //localhost:3000
Referer:http: //localhost:3000/
User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like 
Gecko) Chrome/55.0.2883.87 Safari/537.36

如何在响应标题中启用COR???

7 个答案:

答案 0 :(得分:8)

DO

npm install cors --save

只需在请求所在的主文件中添加这些行。

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

答案 1 :(得分:4)

要启用cors,您可以执行以下操作:

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

请记住,cors是中间件,因此您需要在它之前设置app.use,这样您的收到的请求才会在它们到达您的路线之前通过cors。

您可以根据要使用的端口更改端口。我很确定你也可以用||替换&&来监听多个端口并在那些端口上设置cors。

在raw节点中,我相信你必须使用writeHead,但我不确定原始节点的实现。

答案 2 :(得分:3)

浏览器显示错误,服务器localhost:8080拒绝来自localhost:3000的请求,似乎cors在服务器localhost:8080上没有设置好。

响应头应该是这样的:

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:*

尝试在8080服务器中添加cors标头。

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");
//...

答案 3 :(得分:3)

要解决此问题,首先您必须了解什么是 Access-Control-Allow-Origin:此 Header 的值将是您将向服务器发送请求的主机(例如快递)。

步骤 1:在服务器端允许 cors,(要允许跨域请求,您可以使用 * 代替 http://localhost:3000:

var express = require("express");
var app = express();
 
 
app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*"); // update to match the domain you will make the request from
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
});

第 2 步:只需使用您的 http 客户端,我使用的是 Axios:

var qs = require("querystring");
var axios = require("axios");
const sendEmail = (email, subject, template) => {

    var data = qs.stringify({
        email: email,
        subject: subject,
        template: template,
    });
    var config = {
        method: "post",
        url: "https://abc-domain.com/endpoint",
        headers: {
            "Content-Type": "application/x-www-form-urlencoded",
        },
        data: data,
    };

    axios(config)
        .then(function(response) {
            console.log(JSON.stringify(response.data));
        })
        .catch(function(error) {
            console.log(error);
        });
};

module.exports = sendEmail;

答案 4 :(得分:1)

CORS(跨源资源共享)添加到您的节点,快速应用程序很容易......

您首先需要通过 npm 安装 cors 库,使用以下命令:

npm install cors -S

如果您需要全球,只需向其添加-g标志即可...

然后在快递应用中,执行以下操作:

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

这些也是他们的文档中的其他示例:

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

异步配置CORS:

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

答案 5 :(得分:0)

此代码有助于我解决快递的资源问题。而且,您可以在异步原始配置中轻松使用其他选项。

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

答案 6 :(得分:0)

//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`