简体   繁体   中英

Post request body returning undefined

I'm making a post request using axios and passing in a body like so:

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)
}

However, at the server, I'm getting an undefined when accessing req.body.

  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)
    }
      });

What am I doing that's causing the body to be undefined in the node.js server rather than to be the map that's passed in axios?

Please install body-parser add following code in your js file after const path:

npm install body-parser

const bodyParser = require('body-parser')

app.use(bodyParser);

The bodyParser object exposes various factories to create middlewares. All middlewares will populate the req.body property with the parsed body when the Content-Type request header matches the type option, or an empty object ({}) if there was no body to parse, the Content-Type was not matched, or an error occurred.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM