Node.js body is not parsing

Asked by At

When I try to post some data to my database through an express server, the body does not get parsed.

I have tried to use express.json() and after that not working, I went back to bodyParser.json(). None of these things worked, so I took to the web. I have been watching videos, reading articles, and searching through stack overflow for 2 hours now, and I cannot find a solution.

Client side (react.js):

fetch('http://localhost:7000/users', {
   method: 'POST',
   header: {
      'Content-Type': 'application/json',
      'Accept': 'application/json'
   body: JSON.stringify({
      username: username,
      password: password

Server side (node.js with express):

const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const http = require('http');

const app = express();

app.use(bodyParser.urlencoded({ extended: false }));

const index = require('./routes/index');
const users = require('./routes/users');

app.use('/', index);
app.use('/users', users);

const server = http.Server(app);
const port = 7000;

server.listen(port, () => {
    console.log('Listening on port ' + port);

(The reason I am using an http server instead of app.listen is because I am going to add Not sure if that is important)


const express = require('express');
const router = express.Router();
const mongo = require('mongojs');
const dbuser = SENSITIVE_INFO;
const dbpass = SENSITIVE_INFO;
const db = mongo('mongodb://'+dbuser+':'+dbpass+'', ['users']);

router.get('/', (req, res, next) => {
    db.users.find((err, users) => {
        if (err) {
});'/', (req, res, next) => {
    var body = req.body;
    var data = {
        name: body.username,
        password: body.password


    //, (err, user) => {
    //     if (err) {
    //         res.send(err);
    //     }
    //     res.json(user);
    // });

module.exports = router;

On the client side, I console logged what I was sending to the server and the result was:


On the server side, I console logged what I was receiving and the result was:


{ name: undefined, password: undefined }

Please let me know if I am just being dumb and missing something simple, or if there is something that I should add or change.

Thank you in advance for your help!

1 Answers

Syed Hammad Ahmed On Best Solutions

Its just a typo I think. It should be 'headers' instead of 'header'.

fetch('http://localhost:7000/users', {
 method: 'POST',
 headers: {
  'Content-Type': 'application/json',
  'Accept': 'application/json'
 body: JSON.stringify({
  username: username,
  password: password