Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
209 views
in Technique[技术] by (71.8m points)

javascript - "error": "message": "Cannot read property 'name' of undefined"

So, I'm trying to create a route and I created a route that should manage to POST data and I have been testing it in postman. It looks like a lot of people have got the same problem, but I have not been able to find a solution. I can see the name hasn't got a value but I've also seen a video where it should work with that bit of code. The person I've seen gets the response as JSON in postman, mine gives me the message shown underneath.

My code:

router.post('/', (req, res, next) => {
    const user = {
        name: req.body.name,
        eMail: req.body.eMail
    };
    res.status(201).json({
        message: 'Handling user',
        createdUser: user
    });
});

My code

The answer I get from postman:

{
    "error": {
        "message": "Cannot read property 'name' of undefined"
    }
}

The answer I get from postman

question from:https://stackoverflow.com/questions/66064067/error-message-cannot-read-property-name-of-undefined

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It looks like you're using express. Are you using a body parser? Without one, req.body will always be undefined, which looks like your issue. Try putting this before you define any of your routes.

const bodyParser = require('body-parser');
app.use(bodyParser.json()); // for parsing application/json

Docs


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...