我正在使用 axios 发出一个 post 请求并传入一个像这样的正文:
export const uploadFeatured = (userId, uploadInfo) => async dispatch => {
////console.log("uploading", uploadInfo.mediaName, uploadInfo.video, uploadInfo.description);
const res = await axios.post(domain + '/api/uploadFeatured',
{mediaName: uploadInfo.mediaName,
video: uploadInfo.video,
description: uploadInfo.description});
console.log("response to upload", res)
}
但是,在服务器上,我在访问 req.body 时得到了 undefined。
app.post("/api/uploadFeatured", async (req, res) => {
try {
//////// req.body returning undefined.
console.log("upload featured is ", req.body)
const data = {name:"Name"}
const newFeatured = new Featured(data).save();
const client = algoliasearch('YD', '055b10');
const index = client.initIndex('Humboi');
index.saveObjects([data], {
autoGenerateObjectIDIfNotExist: true
}).then(({ objectIDs }) => {
console.log(objectIDs);
});
console.log("new featured is ", newFeatured);
} catch (e) {
console.log("error ", e)
}
});
我在做什么导致在 node.js 服务器中未定义主体而不是在 axios 中传递的映射?
答案 0 :(得分:0)
请安装 body-parser 在你的 js 文件中的 const 路径之后添加以下代码:
<块引用>npm install body-parser
const bodyParser = require('body-parser')
app.use(bodyParser);
bodyParser 对象公开各种工厂以创建中间件。当 Content-Type 请求标头与 type 选项匹配时,所有中间件都将使用解析的正文填充 req.body 属性,如果没有要解析的正文,则为空对象 ({}),或者 Content-Type 不匹配,或者发生错误。