【发布时间】:2019-01-06 03:47:09
【问题描述】:
我想用 NodeJS 文件替换当前处理从我的网页(仅限 LAN)接收和处理数据的 PHP 脚本。目前,JSON 数据是在 JS 中通过 XMLHttpRequest 发送的:
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 数据吗?
【问题讨论】:
-
您可以在不同的端口上运行您的 node.js 服务器并将您的请求路径更改为类似
/node/server的内容,然后配置您的 Apache 服务器以代理任何以/node开头的请求到您的节点服务器在其端口上。
标签: php node.js http http-post