如何使用Express和Node.js监听已经在监听的服务器上的POST请求?

huangapple go评论69阅读模式
英文:

How to listen to POST requests made to an already listening server using express with nodeJS

问题

我使用Go在8080端口创建了一个本地服务器。该服务器已经处于“监听”状态,因此我无法使用app.listen(8080)访问它,因为服务器已经处于此状态。
这段之前的Go代码正在执行一些POST请求,我希望在使用Express的Node.js脚本中看到这些请求。目前,在我的端上看不到任何请求。

这是我的代码:

import express from 'express';
import bodyParser from 'body-parser';
const app = express();
app.set('port', process.env.PORT || 8080);

app.use(express.urlencoded({ extended: true }));
app.use(bodyParser.json());

app.post('/', function(req, res){
console.log(req.body);
})

setInterval(function() {
}, 1000 * 60 * 60);

我添加了setInterval来使脚本“等待”,以替代app.listen,但我不确定是否会引起任何问题。

提前感谢。

英文:

I created a local server on the 8080 port using go. This server already has the 'listening' status, and I cannot access to it using app.listen(8080) because the server is already in this status.
This previously golang code is doing some POST requests that I would like to see on the nodeJS script using express. Currently, no requests are visible on my side.

So this is my code:

import express from 'express';
import bodyParser from 'body-parser';
const app = express();
app.set('port', process.env.PORT || 8080);

app.use(express.urlencoded({ extended: true }));
app.use(bodyParser.json());

app.post('/', function(req, res){
  console.log(req.body);
})

setInterval(function() {
}, 1000 * 60 * 60);

I added the setInterval to make the script "wait" in substitution to the app.listen, but I'm not sure if it would cause any issue though.

Thanks in advance.

答案1

得分: 0

服务器绑定到运行的端口上。这意味着,在任何给定的机器上,一个服务器只能绑定到一个端口。现在,当Go服务器已经在端口8080上运行时,你的Node服务器不能使用该端口。你需要使用一个不同的端口,并使用新的端口请求新的服务器。

你可以这样做:
Go服务器使用8080端口,http://localhost:8080 -> Go服务器
Node服务器使用8000端口,http://localhost:8000 -> Node服务器

如果你想将所有内容都包装在一个单一的端口下,你需要一个HTTP服务器(如Nginx),然后在那里定义反向代理和路由规则。你可以从这里开始:https://stackoverflow.com/questions/27220678/how-to-redirect-to-specific-upstream-servers-based-on-request-url-in-nginx/27240080

英文:

The server binds to a port that it runs on. This means, on any given machine, one server can only bind itself to one port. Now, when the go server is already running on port 8080, your node server cannot use that port. You'll have to use a different port and then you'll have to request the new server with a new port.

You can do the following:
Go server works on 8080, http://localhost:8080 -> Go server
Node server works on 8000, http://localhost:8000 -> Node server

If you want to wrap this all under a single port, you'll need an http server (like Nginx) and then define reverser proxy and routing rules there. You can start here.

huangapple
  • 本文由 发表于 2021年7月28日 09:03:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/68553217.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定