我正在尝试向我的节点/快速服务器发出POST请求,以发送电子邮件。我想通过请求传递电子邮件的详细信息,但无法在节点端获取数据。
这是我到目前为止注意:电子邮件发送部分是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();
答案 0 :(得分:4)
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());

此:
您需要以可通过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" }
});