我正在使用restify,对于TDD我正在使用mocha测试框架。当我使用post方法从restify客户端测试restify服务器它没有按预期工作。
我的服务器代码如下:
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();
});
});
});
});
当我传递数据为{name:'aruljothi'}时,它正在工作,但就像上面json对象的情况一样,它无效。在服务器req.body中以{}。
2) Expecting 200 status code post /admin/user -> should return 200 status:
Uncaught
AssertionError: InternalServerError: {"message":"{}"}
提前谢谢你。
答案 0 :(得分:0)
我遇到了这个问题,因为通过restify的JsonClient发送对象o
会导致服务器端出现一个空对象{}
。
将其放入代码中,如果
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) {
});
为{}
提供req.body
,请务必使用json bodyparser作为中间件
app.use(bodyParser.json());
然后它应该最终给你所需的{ '42': 23, foo: 'bar' }
。
答案 1 :(得分:0)
我使用JSON.parse解决了完全相同的问题,由于某种原因,var数据未被识别为对象。
describe('core', function () {
describe('/admin/user', function () {
it('POST with data', function (done) {
var data = {
name: "aruljoth1i",
email: "aruljot1h1iparthiban@hotmail.com"
};
data = JSON.parse(data);
client.post('/admin/user', data, function (err, req, res, obj) {
assert.equal(res.statusCode, 200,err);
done();
});
});
});
});
答案 2 :(得分:-1)
请检查此网址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);
});