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(cors());
app.use(bodyParser.json());
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 socket.io. Not sure if that is important)

routes/users.js:

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+'@ds157574.mlab.com:57574/chat-app-1__saahilkhatkhate', ['users']);

router.get('/', (req, res, next) => {
    db.users.find((err, users) => {
        if (err) {
            res.send(err);
        }
        res.json(users);
    });
});

router.post('/', (req, res, next) => {
    var body = req.body;
    var data = {
        name: body.username,
        password: body.password
    };

    console.log(body);
    console.log(data);

    // db.users.save(data, (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:

{"username":"testUser","password":"testPass"}

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

0
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
 })
});