1

I have this endpoint on backend (node, express):

router.post('/createUser', (req, res, next) => {
  try{
    const { user } = req.body;
    if(!user) next(createError(401))
    data.push(user);
    res.status(200).json(user)
  } catch(e) {
    next(e)
  }
})

and this on front (service)

class EmployeeService {
  constructor() {
    this.api = axios.create({
      baseURL: process.env.REACT_APP_BACK_DOMAIN || 'http://localhost:4000',
      withCredentials: true
    })
  }

  getPaginated = (page, size) => this.api.get(`/?page=${page}&size=${size}`).then(({data}) => data)

  createUser = user => this.api.post('/createUser', user).then(({data}) => data)
}

When i receive createUser Request, i take body from req, but it is undefined, i console log "req" and this returned me an incoming message object Why? i need to receive body for push on array :(

the object that i create on front: User object

Adrián
  • 175
  • 9

2 Answers2

0

It seems to me that you are sending the user object wrong, Try this:

user = {id:1,name:"nombre"}

createUser = this.api.post('/createUser', user).then(({data}) => data)

And check if the body arrives to backEnd

Hugo Valenza M
  • 169
  • 1
  • 6
0

This is let answer but...

As you mention you are receiving an object but not able to excess data though req.body

server API and Axios working fine then the problem is parser

try adding parser as shown below and make sure it is before app.use("/", router)

const express = require('express');
const app = express();
var router = express.Router();

// create application/x-www-form-urlencoded parser
app.use(express.urlencoded({ extended: false }));
// parse application/json
app.use(express.json());

app.use("/", router);

for more information check this Express.js req.body undefined

Yash
  • 211
  • 2
  • 14