javascript - Node POST请求-接收数据

标签 javascript node.js express

我正在尝试向我的 Node/express 服务器发出 POST 请求,以发送电子邮件。我想通过请求传递电子邮件的详细信息,但无法获取 Node 端的数据。

这是我到目前为止所得到的注意:电子邮件发送部分是 psuendo 代码

index.js

var jsonDataObj = {'to': 'example@exmpale', 'subject': 'this is the subject','text': 'this is the text',};
const response = await fetch('/api/hello', {
  method: 'post',
  body: jsonDataObj
});

server.js

const express = require('express');
const app = express();
const bodyParser = require("body-parser");

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.post('/api/hello', (req, res) => {

  const msg = {
    to: req.body.to,
    subject: req.body.subject,
    text: req.body.text
  };

  sendEmail(msg);
});

app.listen();

最佳答案

var jsonDataObj = {'to': 'example@exmpale', 'subject': 'this is the subject','text': 'this is the text',};

That is a JavaScript object, not JSON .

当您将其传递给 fetch 时,将通过调用其 toString() 方法将其转换为字符串。

var jsonDataObj = {'to': 'example@exmpale', 'subject': 'this is the subject','text': 'this is the text',};
console.log(jsonDataObj.toString());

这个:

  • 不是 JSON
  • 未进行网址编码
  • 实际上不包含您的任何数据

您需要以可以通过 HTTP 发送的格式对数据进行编码。

例如,这将以多部分格式发送:

var jsonDataObj = {'to': 'example@exmpale', 'subject': 'this is the subject','text': 'this is the text',};
var data = new FormData();
Object.keys(jsonDataObj).forEach(key => data.append(key, jsonDataObj[key]));
const response = fetch('/api/hello', {
  method: 'post',
  body: data
});

...您可以使用 multer 来阅读.

虽然这将使用 bodyParser.urlencoded 应该能够处理的查询字符串进行编码。

var jsonDataObj = {'to': 'example@exmpale', 'subject': 'this is the subject','text': 'this is the text',};
var data = new URLSearchParams();
Object.keys(jsonDataObj).forEach(key => data.append(key, jsonDataObj[key]));
const response = fetch('/api/hello', {
  method: 'post',
  body: data,
  headers: { "Content-Type": "application/x-www-form-urlencoded" }
});

这实际上会使用 JSON:

var jsonDataObj = {'to': 'example@exmpale', 'subject': 'this is the subject','text': 'this is the text',};
var data = JSON.stringify(jsonDataObj);
const response = fetch('/api/hello', {
  method: 'post',
  body: data,
  headers: { "Content-Type": "application/json" }
});

关于javascript - Node POST请求-接收数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49574937/

相关文章:

javascript - 找不到模块 `express` |套接字.io [node.js]

javascript - 如何在不同的端口上运行多个快速服务器?

javascript - 在 Windows 托管站点上运行基本的 node.js

javascript - 为什么复杂类型作用于引用值

javascript - Chrome canvas 2d context measureText 给我奇怪的结果

javascript - 使用数组而不是参数数组

javascript - Express中间件和端点之间如何共享信息?

javascript - jQuery 组合函数

javascript - 解码 xml 并渲染回 Canvas 图形单元格后未在 mxgraph 中显示

node.js - 在渲染时发送到 EJS 的空参数