Dirk
Dirk

Reputation: 2144

simple expressjs PUT handler with jQuery ajax method

I'm building a web application that uses a REST API for communication with the server, built in Node.js using Expres.js. The problem is that I can't seem to read the request body in the PUT requests. My client side code:

$.ajax({
    url: "/api/model/"+this.database,
    type: "PUT",
    contentType: "application/json",
    data: this.model.exportJSON(),
    success: function(data){
        console.log(data);
    }
});

and the server side code (only the important bits):

//in the main file
var express = require("express");
var app = express();

var model = require("./apis/model");

app.put("/api/model/:model", model.put);

app.listen(8000);

//in the module
module.exports = {    
    put: function(req, res){
        console.log(req.body);
        res.json({"hello": "world"});
    }
};

The exportJSON method on the model produces an object, not anything empty, but on the server side console.log I get undefined, what am I doing wrong?

EDIT: The Chrome developer console reveals that the data is sent just fine, so it has to be something on the server side

Upvotes: 0

Views: 1393

Answers (1)

srquinn
srquinn

Reputation: 10481

Because you are sending a content type of 'application/json', you need to add the body-parser middleware:

$ npm install body-parser

And then use it thusly:

//in the main file
var express = require("express");
var app = express();
var body = require('body-parser');

app.use(body.json());

app.put("/api/model/:model", function (req, res){
    console.log(req.body);
    res.json({"hello": "world"});
});

app.listen(8000);

And then make the request

$ curl -i -H "Content-Type: application/json" -X PUT -d '{ "key": "value" }' http://localhost:8000/api/model/foo

And this will log

{ "key" : "value" }

Make sure you are defining the app.use(body) call BEFORE you define a route.

Upvotes: 2

Related Questions