1

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"
 }
}

1 Answer 1

1

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);
})
Sign up to request clarification or add additional context in comments.

2 Comments

This problem was solved. My nodeJs version was old, when I installed the new version then it was solved. Thanks for your answer.
Very unexpected that simply upgrading NodeJS solved the issue _(your code just doesn't look to me as if it should return anything), but at least you got it working.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.