如何使用 express 启用 cors nodejs?

IT技术 javascript node.js express cors
2021-01-26 02:21:12

总之,我正在使用称为基石的 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服务器必须支持跨源资源共享,否则图片加载失败。如果您无法在要从中加载 DICOM P10 实例的 Web 服务器上启用 CORS,则可以使用反向代理。这是一个基于 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”的模式,

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

更新!

服务器响应如下;

响应头

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

如何在响应头中启用CORS??

6个回答

npm install cors --save

并将这些行添加到您的请求所在的主文件中。

const cors = require('cors');
const express = require('express');
const app = express();
app.use(cors());
app.options('*', cors());
@O.Jones 当使用 cors 作为全局中间件时,app.use(cors());您不需要也为其分配OPTIONS请求。请参阅此处的注释:expressjs.com/en/resources/middleware/...
2021-03-17 02:21:12
这就是答案——预检请求在 HTTP 中使用 OPTIONS 动词,并.options()处理这些动词。
2021-04-11 02:21:12

要启用 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。

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

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

我的问题来自端口 8080,因为我将 Access-Control-Allow-Origin 添加到端口 8080,这是 dcm4chee 服务工作的地方,它为我提供 DICOM 文件,我的应用程序在端口 3000 上工作并且已经在端口 3000 中启用了 cors,但是当我在提供 DICOM 图像的服务工作的端口 8080 中启用 CORS 时,这就是我的问题。
2021-03-23 02:21:12

CORS(Cross-Origin-Resource-Sharing) 添加到您的节点,express 应用程序非常容易...

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

npm install cors -S

如果您在全球范围内需要它,只需-g为其添加标志...

然后在您的express 应用程序中,执行以下操作:

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

这些也是他们文档中 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')
})
我在这里有点晚了,最新的 Express Router 是一个单独的module,我们将不得不依赖它。那么,如何将 cors 应用于异步路由?例如: router.get('/', cors(corsOptions), async (req, res ) => res.json('test')
2021-03-26 02:21:12

浏览器显示的错误是,server localhost:8080 拒绝了来自localhost:3000 的请求,看来cors 在server 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");
//...
app.use(cors());在服务器 8080 上使用
2021-03-20 02:21:12
不需要在3000端口配置cors,页面在3000上服务。这里的情况是浏览器在3000上打开一个页面,然后请求一个8080上服务的api。所以,服务器8080需要设置为允许跨域请求。
2021-03-23 02:21:12
你能推荐一个api吗?
2021-04-01 02:21:12
这是我在端口 8080 上的问题 dcm4chee 工作,我该如何添加?如何从在端口 3000 上运行的应用程序配置它?
2021-04-03 02:21:12
这是什么我不明白,抱歉无知,但由于我正在使用 NODEJS 并且我的应用程序在端口 3000 中,而 DCM4CHEE 在端口 8080 中,我无法从端口 3000 的应用程序中收敛 CORS,我如何为端口 3000 应用程序配置 DCM4CHEE 使用的 8080 端口 CORS,这是 DICOM 提供商?我不知道我是否解释得很好,抱歉 = (probe with app.use (cors ({source: 'localhost: 8080';}));) 在我的应用程序的 app.js 中使用端口 3000
2021-04-08 02:21:12

这段代码帮助我解决了快递的资源 cors 问题。并且您可以通过异步源配置轻松使用其他选项。

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