【发布时间】:2020-10-10 00:01:57
【问题描述】:
我在前端使用 Angular 并向使用 Express 构建的后端发送发布请求。
这是 Angular 代码的外观:
addEntry() {
let type = "Random Type";
let location = "Random Location";
let date = new Date();
let results = [
{ name: "my first name", age: 23 },
{ name: "new second name", age: 35 },
];
return this.http.post<{ message: string }>(
this._url + "/myendpoint/add",
{ type, location, date, results }
);
}
这就是 express 代码的样子:
router.post(
"/add",
middleware.verifyToken,
async function (req, res) {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(422).json(errors.array());
}
try {
let userID = req.tokenData.userID;
let user = await User.findOne({ _id: userID });
if (user === null || user.length <= 0) {
return res.status(422).json("Could not add entry");
} else {
let type = req.body.type;
let location = req.body.location;
let date = req.body.date;
console.log(req.body);
let results = req.body.results.map(async (el) => {
let result = await Entry.findOne({ name: el.name });
return {
name: result.name,
age: el.age,
};
});
[some more code ...]
}
} catch (err) {
console.log(err);
return res.status(422).json(err);
}
}
);
控制台日志输出:
{
type: 'Random Type',
centre: 'Random Location',
date: '2020-06-19T16:50:25.357Z',
results: '[object Object]'
}
我也收到了这个错误,可能是因为结果显示为“[object Object]”;
TypeError: req.body.results.map is not a function
如何在 Express 中获取结果数组而不是 '[object Object]'?我在 Express 中启用了以下设置:
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
【问题讨论】:
-
您是如何尝试对 POST 正文进行字符串化的?
JSON.stringify({ type, location, date, results }) -
感谢您的帮助...它仍然无法自行工作...非常奇怪的行为。我尝试将它与 JSON 解析、encodeURIComponent 和 decodeURIComponent 结合起来,但它似乎可以工作。
-
您不需要对字符串化的 JSON 进行编码,因为您没有在 URI/URL 中发送它。但是您可能需要将
http请求中的Content-Type标头设置为application/json。Content-Type标头将告诉 Express 如何处理正文中的数据。 -
我将 content-type 标头设置为 application/json,但 Angular 会转义 JSON.stringify() 并且我在后端收到的是包含大量“
-
如果你不对 JSON 正文进行字符串化,而是放入
application/jsonContent-Type标头,那么请求正文是什么类型(typeof(req.body))?
标签: node.js angular express http