javascript - 将数据从 Javascript 发送到 Node.js

标签 javascript node.js express

我正在尝试创建一个非常基本的功能,

假设我的 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/

相关文章:

javascript - 使用 jQuery 遍历 <div> 列表

javascript - Meteor/Iron 路由器上的动态路径

javascript - 为什么在 Javascript 中使用正则表达式来验证经纬度?

javascript - 如何将 Node 变量传递给外部javascript?

node.js - 如何从 io.use 设置或删除 cookie

node.js - 带子路由器的 Express 路由器

c# - ajax post 无法在 C# 中正常工作

node.js - Karma 不会运行(socket.io 抛出错误)

javascript - 错误 EACCES 权限被拒绝 mkdir multer node.js

node.js - NodeJS 部署到 AWS Beanstalk 错误