我正在尝试创建一个非常基本的功能,
假设我的 javascript 数据是
常量数据 = 1234;
如何将此数据发送到我使用 Express 框架创建的 Node 服务器
const express = require("express");
const app = new express();
app.get("/", (req, res) => {
res.send("home");
});
app.post("/datastream", function (req, res) {
res.send('You sent the data: "' + req.body.data + '".');
});
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`server started on port ${PORT}`));
最佳答案
如果您想从浏览器发送它并且您的服务器在本地运行:
const data = 1234
fetch('http://localhost:5000/datastream', {
method: 'POST',
body: JSON.stringify({ data }),
headers: { 'Content-Type': 'application/json' }
})
.then(response => response.text())
.then(data => console.log(data))
.catch(err => console.log(err))
现在您需要安装 body-parser
中间件,以便能够反序列化您的 JSON 数据 npm install body-parser
并将其附加到您的应用程序。将其添加到您的服务器代码中:
const bodyParser = require('body-parser')
// ...
app.use(bodyParser.json())
如果一切顺利(您的服务器在指定端口上运行),那么在运行浏览器代码后,它应该记录您发送了数据:1234.
关于javascript - 将数据从 Javascript 发送到 Node.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61352179/