Search code examples
node.jsreactjsrestaxiosapi-design

Axios Post Request Sending Undefined


I am having an issue with sending data from an Axios post request to my ExpressJS post route. When I try to read the data sent on the post route it shows as undefined. This is my Axios post:

axios.post('http://localhost:3000/temps/heating', {
    messageType: 'heating',
    toggle: 'on'
}).then(res => {
    console.log(res);
}).catch(e => {
    console.log(e)
})

and this is my ExpressJS Post route below. I have tried to use req.params req.body & req.messageType

routes.post('/heating', (req, res, next) => {
    const messageType = req.data;
    console.log(messageType);
})

I thought that because Axios is sending "data" I request data on the NodeJS post route?

Thanks


Solution

  • In your express app make sure to use body-parser: https://expressjs.com/en/resources/middleware/body-parser.html

    const bodyParser = require('body-parser');
    app.use(bodyParser.json());
    

    In your route you should then be able to access req.body.messageType:

    routes.post('/heating', (req, res, next) => {
        const messageType = req.body.messageType;
        console.log(messageType);
    })