我有一个 node.js 应用程序,用于与另一台服务器提供的 REST API 进行交互。我想使用express.js公开一个Web界面(html + css + javascript)来控制第一个应用程序。
如何让浏览器与服务器对话并让它执行 node.js 操作,例如从该机器使用 http 或写入其文件系统?我尝试使用 XMLHttpRequest,但 HTTP 请求是由我的本地 PC 发送的,而不是从我的服务器发送的。
我找到的唯一解决方案是在我的 Web 界面的 javascript 中使用 XMLHttpRequest 来调用服务器上的一些中间件功能,但我遇到了一些问题:当我发出 POST 请求时,我无法从服务器读取数据。我使用 FormData 及其附加方法来制作 POST 请求的“正文”,然后使用 express 中的 body-parser 来读取该正文,但结果总是空的。还尝试更改 header 的“Content-Type”。
有什么建议吗?还有比我更好的解决方案吗(我认为效率不高)?
最佳答案
正如 Jonas 所指出的,使用 Node 服务器作为代理将是正确的方法。
我为前端和后端应用程序提供示例代码。希望这对您有帮助。
- 前端应用代码
<html>
<head>
<script type="text/javascript">
function sendData(data) {
if (!data) {
// lets define some dummy data for testing
data = { somekey: "somevalue", anotherkey: "anothervalues" };
}
var XHR = new XMLHttpRequest();
var FD = new FormData();
// Push our data into our FormData object
for (name in data) {
FD.append(name, data[name]);
}
// Define what happens on successful data submission
XHR.addEventListener("load", function(event) {
alert("Yeah! Data sent and response loaded.");
alert(event.target.responseText);
});
// Define what happens in case of error
XHR.addEventListener("error", function(event) {
alert("Oops! Something went wrong.");
});
// Set up our request
XHR.open("POST", "http://path/to/your/nodejs/server/app");
// Send our FormData object; HTTP headers are set automatically
XHR.send(FD);
}
</script>
</head>
<body>
<button onclick="sendData()">Send Test Request to the Server</button>
</body>
</html>
- 后端应用代码
const http = require('http'); const express = require('express'); const bodyParser = require('body-parser'); const app = express(); app.use(bodyParser.urlencoded({ extended: false })); app.get('/', (req, res) => res.send('Yeah! Server is UP! Post some data')); app.post('/', (req, res) => { // You'll see the posted data in req.body, simply for testing purpose return it back to the calling user res.json(req.body || {}); }); const server = http.createServer(app); server.listen(3000); server.on('error', console.error); server.on('listening', () => console.log('Listening on 3000')); process.on('exit', (code) => console.warn('Server terminated with code=' + code));
请注意,要运行此后端应用程序,您必须安装以下 npm 软件包:express、body-parser
关于javascript - 使用Express服务器来控制nodejs应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51799700/