0

I am trying to send a post request using Axios and I also want to access the data from the server. My code is

axios({
    method: 'post',
    url: '/register/',
    headers: {'Content-Type' : 'application/json'},
    body: JSON.stringify({fname, lname, username, email, pass})
})
.then((res) => {
    console.log(res)
})
.catch(err => {
    console.log(err)
})

// and my backend code is
const express = require('express')
const router = express.Router()

router.post('/', async (req, res, next) => {
    const firstname = ''
})

Request is send properly and my server also accepts the request. but i do not know how to get the values from my server.

please help me. code is working fine just help me in getting the values on server side code

Shanu Raj
  • 1
  • 1

1 Answers1

1
  1. Unlike fetch, axios does not require you to stringify the body of the post request. You can just post like so:
axios({
    method: 'post',
    url: '/register/',
    headers: {'Content-Type' : 'application/json'},
    body: {fname, lname, username, email, pass}
})
...
  1. Assuming you are posting to the correct endpoint (e.g. /register), on the server side, you would access it this way:
router.post('/register', (req, res) => {
    const fname = req.body.fname;
    ...
})

Note that this assumes your backend is properly configured. If all you're running is the code you showed, it won't work as you would need stuff like:

const app = express();
app.use(express.json());
...
...
app.listen(YOURPORT, () => {
    console.log(`Listening to requests on port YOURPORT...`);
});
codemonkey
  • 5,572
  • 3
  • 17
  • 30
  • i tried your code req.body.fname but i am getting undefined and i also removed json.Stringify() and endpoint is correct – Shanu Raj Feb 08 '21 at 06:21
  • @ShanuRaj Your backend app is not properly configured. Check out the last paragraph of my answer. – codemonkey Feb 08 '21 at 06:40