[英]How to enable cors nodejs with express?
總之,我正在使用像 api 這樣的 dicom 文件的查看器,稱為基石,為此我連接到 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,我需要在標頭響應中而不是在 header 請求中激活或添加“Access-Control-Allow-Origin”的模式,
如何在 dcm4chee 從 NODEjs 運行的端口 8080 上添加 CORS?
更新!
服務器響應以下內容;
響應 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
請求 HEADER
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
如何在響應 HEADER 中啟用 CORS?
做
npm install cors --save
只需將這些行添加到您的請求所在的主文件中。
const cors = require('cors');
const express = require('express');
const app = express();
app.use(cors());
要啟用 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。
在原始節點中,我相信您必須使用 writeHead,但我不確定原始節點的實現。
將CORS(Cross-Origin-Resource-Sharing)添加到您的節點,express 應用程序非常容易......
您需要先通過npm安裝cors庫,使用以下命令:
npm install cors -S
如果您需要全局,只需在其中添加-g
標志...
然后在您的快速應用程序中,執行以下操作:
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')
})
瀏覽器顯示的錯誤意味着,服務器 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");
//...
});
要解決這個問題,首先您必須了解什么是Access-Control-Allow-Origin :此 Header 的值將是您將向服務器發送請求的主機(例如 express )。
第 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;
在我添加http://
請求 url 之前,CORS 在 localhost 上不起作用
不工作localhost:3001
工作正常http://localhost:3001
這就是我的工作代碼最后的樣子
節點端
var cors = require('cors')
const app = express();
app.use(cors()); // Make sure this line comes right after express()
前端側
let response = await axios.post("http://localhost:3001/uploadFile", formData);
// the http:// is required cors to work for localhost
這段代碼幫助我解決了 express 的資源 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
//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`
在您的路由處理程序中添加以下內容
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
例如,而不是這個
app.get("/monsters", (req, res) => {
const arr = [
{
name: "Abanoub",
id: "215",
},
{
name: "Mena",
id: "sd5",
}
];
res.send(arr);
});
使用我之前提到的標題。 所以路由處理程序將是這樣的:
app.get("/monsters", (req, res) => {
const arr = [
{
name: "Abanoub",
id: "215",
},
{
name: "Mena",
id: "sd5",
}
];
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.send(arr);
});
我也遇到了這個問題。 為了解決這個問題,我使用了 CORS 模塊並將其導入到我的路由中:
import cors from 'cors';
const router = new Router();
router.get('/posts', cors(), PostController.getAll);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.