Richardson
Richardson

Reputation: 2285

how to acess data from axious post request on node backend?

I am trying to send a data object to backend using axios... the question is should I use axios at back end as well ? I don't seem to be able to get the value.

 axios({
      method: 'post',
      url: '/encrypt',
      data: {
        firstName: 'Fred',
        lastName: 'Flintstone',
      },
      //headers: {'Authorization': 'Bearer ...'}
    });

app.post('/encrypt', (request, response) => {
  console.log(request.body, 'Request................');
});

Upvotes: 0

Views: 151

Answers (2)

Noa Yarin Levi
Noa Yarin Levi

Reputation: 191

Try to fix your code and write according to the syntax. Axios returns a promise.

axios.post('/encrypt', {
    firstName: 'Fred',
    lastName: 'Flintstone' }
).then(function (response) {
    console.log(response)}).catch(function (error) {
    console.log(error)
});

Upvotes: 1

kah608
kah608

Reputation: 565

Make sure to include the body parser.

const express = require('express')
const app = express()
const port = 3000
const bodyParser = require('body-parser')

// create application/json parser
const jsonParser = bodyParser.json()

app.post('/encrypt', jsonParser, (req, res) => {
  console.log(req.body);
  res.send(req.body);
})

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`)
})

And the client side

const axios = require('axios').default;
axios({
      method: 'post',
      url: 'http://localhost:3000/encrypt',
      data: {
        firstName: 'Fred',
        lastName: 'Flintstone',
      },
      //headers: {'Authorization': 'Bearer ...'}
    });

Upvotes: 1

Related Questions