1

server.js:

    var express = require('express');
    var app = express();
    loggedIn = {};

    app.use('/',express.static('www')); // static files

    app.listen(8080, function () {
      console.log('Port 8080!');
    });

    app.get('/user', function(req, res) {
        if (typeof req.param('user') != 'undefined') {
            user = req.param('user');
            res.status(200).send('Works');
        }
    });

    app.post('/user', function(req, res) {
            user = req.param('user');
            if (typeof users[user] != 'undefined') {
                return res.status(405).send('Access Forbidden');
            } else {
                   loggedIn[user] = "";
                   res.status(201).send('New User');
            }
        }
    });

client.js requests:

    $.ajax({
        method: "GET",
        url: "/user",
        data: {"user" : user},
        dataType: "application/json",
        success: function(data) {
            // success
        },
        error: function() {
            // error case
        }
    });

    $.ajax({
        method: "POST",
        url: "/user",
        data: {"user" : user},
        dataType: "application/json",
        success: function(data) {
            // success
        },
        error: function() {
            // error case
        }
    });

Even though the GET request works exactly as expected and passes the parameter here, for some reason, the post request doesn't. In firebug, I notice the POST request receives no parameters whatsoever (POST user) while GET request does (GET user?user=XYZ). I am really at a loss right now.

1 Answers1

1

You have to tell your express app to parse the request body

app.use(express.bodyParser());

for express 4+

var express    = require('express')
var bodyParser = require('body-parser')

var app = express()

// parse application/json
app.use(bodyParser.json())

For reference goto https://expressjs.com/en/4x/api.html#req and look at the section titled req.body

Molik Miah
  • 132
  • 7
Abhijeet Ahuja
  • 5,596
  • 5
  • 42
  • 50
  • I've tried this, but it gives me the error of middleware needing to be separately installed (I'm on express 4.0). However when I try installing it with "npm install --save body-parser", it doesn't let me (unknown system error -122, something to do with mkdir). – SwervinPervan Mar 30 '17 at 00:49
  • 1
    Finally managed to install body-parser, use req.body. on all instances and it still isn't working. It's still hanging while having zero parameters on the POST. When I tried forcing ContentType to application/json in the request, it gave me 'Unexpected token u', meaning I was passing something undefined, even though the data being passed is clearly defined and, I've checked, all the respective values show up in the Firebug DOM section. I'm really lost. – SwervinPervan Mar 30 '17 at 04:25
  • server didn't receive my parameters – Gowtham Sooryaraj May 01 '19 at 14:57