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

Time:03-04

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

CodePudding user response:

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

CodePudding user response:

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