在NodeJS中启用CORS

Enabling CORS in NodeJS

本文关键字:CORS 启用 NodeJS      更新时间:2023-09-26

我有一个NodeJS服务器在带有IP的server机器上运行。NodeJS服务器代码正常工作。例如,我可以使用以下telnet命令进行连接

telnet <ip_server> <port>

或通过curl

curl -d "{}" "http://<ip_server>:<port>/"

我需要通过另一台具有IP的机器访问CLIENT。但是,telnet不会连接,curl返回connection refused错误。只有从CLIENT ping SERVER才能工作。从长远来看,我需要从CLIENT浏览器中加载的Javasrcipt代码访问SERVER。在Firefox中执行此操作时,我可以在开发者控制台中看到以下错误消息

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://<ip_server>:<port>/. This can be fixed by moving the resource to the same domain or enabling CORS.

在过去的几个小时里,我一直在尝试在NodeJS服务器代码中启用CORS。我尝试了各种版本来做这件事,我在网上找到了

...
var express = require('express');
var cors = require('cors')
...
var app = express();
 // Version A
app.all('/*', function(req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
  res.header('Access-Control-Allow-Headers', 'Content-Type');
  next();
});
// Version B
app.use(function (req, res, next) {
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
  res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
  res.setHeader('Access-Control-Allow-Credentials', true);
  next();
});

// Version C (using the "cors" package)
app.use(cors());
app.options('*', cors());

但似乎没有什么不同。虽然telnetcurl命令在从SERVER调用时有效,但在从CLIENT尝试时无效。我在这里想念什么?

(我知道阻止跨域请求是一种鼓励的安全机制。然而,这只是一种纯粹的实验性设置,我需要一个虚拟机(CLIENT)来访问我的本地PC(SERVER),运行NodeJS服务器代码。)

编辑:应要求,以下是相关客户端代码片段。我使用NodeJS代码进行HTTP访问和连接到WebSocket。正如我所提到的,从客户端运行一切都很好

...
doAjaxRequest : function(serverUrl, method, data, callback) {    
  $.ajax({
    url: serverUrl, type: method, data: data, dataType: "json",
    success: function(response, textStatus, jqXHR){ callback(response); },
    error: function(jqXHR, textStatus, errorThrown){ },
  });
},
updateBoundingBox : function(endpoint, lat1, lng1, lat2, lng2) {
  var url = "http://<ip_server>:<port_http>/...";
  this.doAjaxRequest(url, "post", { }, Utility.bind(this, this.onBoundingBoxUpdated));
},
...
if ("WebSocket" in window) {
  websocket = new WebSocket("ws://<ip_server>:<port_ws>/");
}

编辑2:以下是我从客户端访问SERVER:的不同方式中收到的错误消息

// Browser
// Connect to WebSocket
Firefox can't establish a connection to the server at ws://<ip_server>:<port_websocket>/
// HTTP Request
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://<ip_server>:<port_http>/. This can be fixed by moving the resource to the same domain or enabling CORS.

// TELNET
$ telnet <ip_server> <port_http>
Trying <ip_server>...
telnet: Unable to connect to remote host: Connection refused

// CURL
curl -d "{}" "http://<ip_server>:<port_http>/"
curl: (7) Failed to connect to <ip_server> port <port_http>: Connection refused

// ping <ip_server> (works fine)

一个问题可能是客户"各不相同"。telnet和'curl'我直接从具有本地IP(192.168.xxx.xxx)的虚拟机调用。使用浏览器时,CLIENT在具有全局IP的路由器/代理机上运行。当我尝试在路由器/代理机器上执行"telnet"answers"curl"时,命令会挂起。他们没有连接,但我也没有收到任何拒绝连接的错误。

有些人真的必须首先寻找最简单的解决方案。在排除了(几乎)其他任何问题之后,我最终检查了防火墙问题。事实上,客户端上安装了ufw。在我允许访问所需的端口后,一切都很顺利。

谢谢大家的评论!他们确实让我不断地寻找,终于找到了正确的方向。