首页 > 解决方案 > 是否可以在不创建服务器的情况下在 NodeJS 中获取 POST 数据?

问题描述

我想用 NodeJS 文件替换当前处理从我的网页(仅限 LAN)接收和处理数据的 PHP 脚本。目前,JSON 数据通过 XMLHttpRequest 在 JS 中发送:

var xhttp = new XMLHttpRequest();
var url = "/server.php";
xhttp.open("POST", url, true);
xhttp.setRequestHeader("Content-Type", "application/json");
xhttp.onreadystatechange = function () {
    ...
};

xhttp.send(content);

显然, server.php 是我要替换的文件。在这个文件中,我收到这样的数据:

$stringHttp = file_get_contents("php://input");

我已经广泛搜索了如何在 NodeJS 中做这样的事情,但我发现的所有东西都使用这个基本布局:

http.createServer((request, response) => {
    ...
}).listen(8091);

现在,由于我的网页由 Apache 托管,因此可能无法在同一端口上创建此服务器。至少,这是我从尝试运行 NodeJS 文件时收到的错误消息中得到的:

events.js:183
      throw er; // Unhandled 'error' event
      ^

Error: listen EADDRINUSE :::8091
    at Object._errnoException (util.js:992:11)
    at _exceptionWithHostPort (util.js:1014:20)
    at Server.setupListenHandle [as _listen2] (net.js:1355:14)
    at listenInCluster (net.js:1396:12)
    at Server.listen (net.js:1480:7)
    at Object.<anonymous> (/var/www/apache/testNode.js:15:4)
    at Module._compile (module.js:652:30)
    at Object.Module._extensions..js (module.js:663:10)
    at Module.load (module.js:565:32)
    at tryModuleLoad (module.js:505:12)

所以基本上,我正在寻找一个 NodeJS 替代file_get_contents("php://input"). 因此我的问题是:您能否在不创建服务器的情况下在 NodeJS 中获取 POST 数据?

标签: phpnode.jshttphttp-post

解决方案


不,不是。

在您的 PHP 版本中,您有一个服务器。它是 Apache,它使用(例如)mod_php 来执行 PHP。

如果您使用 Node.js 执行程序,那么您需要某种方式来获取对程序的 HTTP 请求。这涉及运行服务器。

可能无法在同一端口上创建此服务器

不,您需要在不同的端口上运行它。(然后要么直接发布到它,要么将 Apache 配置为在它前面充当代理)。


推荐阅读