我正在尝试向我的 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/