I am using restify, for TDD I am using mocha test framework. When I testing restify server from restify client with post method It is not working as expected.
My server code is below :
exports.post_user = function(req,res,next) {
var body = req.body;
if (!body.name || !body.email) {
throw Error(JSON.stringify(body));
}
// Checking duplicate user before save user information into database
User.findOne({ email: body.email }, function (err, user) {
if(err) { req.log.error(err); }
if (!err && user != null) {
res.send(user);
} else {
var user = new User({
oauthID: Math.random(),
name: body.name,
email: body.email,
created : Date.now()
});
// Profile not available then save information and return response
user.save(function(err) {
if (err) {
console.log(err);
req.log.error(err);
} else {
res.send(user);
};
});
};
});
};
describe('core', function () {
describe('/admin/user', function () {
it('POST with data', function (done) {
var data = {
name: "aruljoth1i",
email: "aruljot1h1iparthiban@hotmail.com"
};
client.post('/admin/user', data, function (err, req, res, obj) {
assert.equal(res.statusCode, 200,err);
done();
});
});
});
});
when I am passing data as {name:'aruljothi'} it is working but as in the case of above json object it is not working. In server req.body is coming as {}.
2) Expecting 200 status code post /admin/user -> should return 200 status:
Uncaught
AssertionError: InternalServerError: {"message":"{}"}
Thankyou in advance.
I came across this question, because sending an object o via restify's JsonClient resulted in an empty object {} on the server side.
To put it in code, if something like
var express = require('express');
var bodyParser = require('body-parser')
var app = express();
app.use(bodyParser.urlencoded())
app.listen(12345, function() {
app.post('/', function(req, res) {
console.log(req.body);
res.end();
})
})
var restify = require('restify');
var client = restify.createJsonClient({
url: 'http://localhost:12345',
version: '*',
});
var some_object = {'foo': 'bar', '42': 23}
client.post('/', some_object, function(err, req, res, obj) {
});
gives you {} for req.body, make sure to also use the json bodyparser as middleware with
app.use(bodyParser.json());
Then it should finally give you the desired { '42': 23, foo: 'bar' }.
please check this url http://mcavage.me/node-restify/#JsonClient
client.post('/foo', { hello: 'world' }, function(err, req, res, obj) {
assert.ifError(err);
console.log('%d -> %j', res.statusCode, res.headers);
console.log('%j', obj);
});