php - 是否可以在不创建服务器的情况下在 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 数据?
解决方案
不,不是。
在您的 PHP 版本中,您有一个服务器。它是 Apache,它使用(例如)mod_php 来执行 PHP。
如果您使用 Node.js 执行程序,那么您需要某种方式来获取对程序的 HTTP 请求。这涉及运行服务器。
可能无法在同一端口上创建此服务器
不,您需要在不同的端口上运行它。(然后要么直接发布到它,要么将 Apache 配置为在它前面充当代理)。
推荐阅读
- python - Google Places API:请求有年度限制吗?
- swift - 在我的 timeZone 中的字符串日期错误
- kubernetes - 在 Azure Kubernetes 集群中使用新的 relic 进行应用程序监控
- javascript - 使用唯一键更新 Javascript 对象嵌套值
- macos - 在 Mac 上找不到 Tensorflow 模块
- vba - 为什么这个查找功能很慢?
- php - CGI 从事 Zend Engine 代码编译的地方
- arrays - 遍历 4 组
- vue.js - Vue.js单文件组件循环报错
- java - JSch ChannelSftp.put 方法 RESUME 模式