pac
pac

Reputation: 241

Why I don't get the req.body on one route ? Node JS

Hello I have following problem with my Node JS Application:

I want to do an authentication, but when I send a POST on that route I get "req.body.username = undefined".

Its only on this route, other routes get the req.body without problems.

Debug: req.body undefined

Packages:

var config = require('./config');
var express = require('express');
var app = express();

var path = require("path");
var bodyParser = require('body-parser');

var bcrypt = require('bcrypt');
var bcryptSaltRounds = 10;
var jwt = require('jsonwebtoken');
var cors = require('cors');

app.set('superSecret', config.secret);

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

app.use(express.static('public'));
app.options('*', cors());
app.use(cors());

app.use(express.static(path.join(__dirname, 'public')));

Here is the server route:

app.post('/auth', function (req, res, next) {
    var username = req.body.username;
    var password = req.body.password;

    User.findOne({
        where: { username: username}
    }).then(function (user) {
        if(user){
            bcrypt.compare(password, user.password).then(function (passcheck) {
                if(passcheck){
                    var jwtUser = {
                        username: user.username,
                        firstname: user.firstname,
                        lastname: user.lastname,
                        acceslevel: "all"
                    };

                    //var mysuperSecretPwd = app.get('superSecret');

                    var token = jwt.sign(jwtUser, app.get('superSecret'), {
                        expiresIn: 1 // expires in 24 hours
                    });

                    res.json({
                        success: true,
                        message: 'Theres your key',
                        token: token
                    });
                }else{
                    res.status(401).json({
                        success: false,
                        message: 'Authentification failed. Password or User wrong'
                    });

                }
            });
        }else{
            res.status(401).json({
                success: false,
                message: 'Authentification failed'
            });
        }
    }).catch(next);
});

Here is the ajax request:

$('#btnRegister').click(function () {

        var firstname = $('#txtFirstnameRegister').val();
        var lastname = $('#txtLastnameRegister').val();
        var username = $('#txtUsernameRegister').val();
        var password = $('#txtPasswordRegister').val();

        if(firstname == "" || lastname == "" || username == "" || password == ""){
            msg ="Please fill the fields.";
            showInfo(msg);
        }else{
            $('#msgInsteadOfAlert').hide(300);

            var userObject = {
                firstname: firstname,
                lastname: lastname,
                username: username,
                password: password
            };

            $.ajax({
                method: post,
                url: baseUrl + postUser,
                data: userObject,
                success: function () {
                    //TODO: CHECK RESPOND IF USER EXISTS
                    var msg = "User: " + username + " successfully added.";
                    showInfo(msg);
                },
                error: function (xhr, status, errorThrown) {
                    showErrorMessage(xhr, status, errorThrown);
                }
            });
        }
    });

Thank you in advance.

Upvotes: 1

Views: 301

Answers (2)

user7560588
user7560588

Reputation:

You must declare the method of your Ajax as a string POST:

$('#btnRegister').click(function () {
  var firstname = $('#txtFirstnameRegister').val();
  var lastname = $('#txtLastnameRegister').val();
  var username = $('#txtUsernameRegister').val();
  var password = $('#txtPasswordRegister').val();

  if (firstname == "" || lastname == "" || username == "" || password == "") {
    msg ="Please fill the fields.";
    showInfo(msg);
  } else {
    $('#msgInsteadOfAlert').hide(300);

    var userObject = {
      firstname: firstname,
      lastname: lastname,
      username: username,
      password: password
    };

    $.ajax({
      method: "POST",
      url: baseUrl + postUser,
      data: userObject,
      success: function () {
        //TODO: CHECK RESPOND IF USER EXISTS
        var msg = "User: " + username + " successfully added.";
        showInfo(msg);
      },
      error: function (xhr, status, errorThrown) {
        showErrorMessage(xhr, status, errorThrown);
      }
    });
  }
});

Upvotes: 1

Michael Lorton
Michael Lorton

Reputation: 44376

Perhaps the problem is that the body of the post is not declared as JSON. Try it like this:

        $.ajax({
            method: "POST",
            url: baseUrl + postUser,
            data: userObject,
            contentType: "application/json",
            success: function () { 
        ...

Upvotes: 0

Related Questions