Taher
Taher

Reputation: 19

Express POST request from react return empty object

I am trying to send object data from the client app, but it doesn't return server-side only return an empty object. I have no errors and after submit in the console.

Client Side using this:

const url = `http://localhost:5000/addUser`;
    fetch(url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(userData)
    }).then(res => console.log(res))

Server-side I use:

const express = require('express')
const cors = require('cors')
const bodyParser = require('body-parser')
require("dotenv").config()
const port = process.env.PORT || 5000;
const { MongoClient } = require('mongodb');

const app = express()
app.use(cors())
app.use(express.json())
app.use(bodyParser.json({
limit: '50mb',
parameterLimit: 100000
}))
app.post('/addUser', (req, res) =>{
const newUser = req.body;
console.log('added new user', newUser)
})

server side package.json

{
  "name": "server",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
 "start": "nodemon index.js",
 "test": "echo \"Error: no test specified\" && exit 1"
},
 "author": "",
 "license": "ISC",
"dependencies": {
"body-parser": "^1.19.0",
"cors": "^2.8.5",
"dotenv": "^10.0.0",
"express": "^4.17.1",
"mongodb": "^3.6.10",
"nodemon": "^2.0.10"
 }
}

Upvotes: 1

Views: 424

Answers (1)

Kelvin Schoofs
Kelvin Schoofs

Reputation: 8718

Your question is a bit ambiguous, but I assume the problem is that your .then(res => console.log(res)) on the client doesn't log the new user.

Your server isn't actually sending a reply back though. Read the Express documentation again, but basically it would look like something like this:

app.post('/addUser', (req, res) =>{
    const newUser = req.body;
    console.log('added new user', newUser);
    // Send HTTP status code 200 back, with the `newUser` in JSON format as body
    res.status(200).json(newUser);
})

Upvotes: 1

Related Questions