I am writing spec for testing RESTful api. The module I use to make http request is standard http module in nodejs.
If I don't specify the 'Content-Length' in header, then the request is made successfully, but I specify the length by
options.headers['Content-Length'] = post_data.length;
, then it is a bad request with 400 error code. I searched stackoverflow for Content-Length related question, but got no inspiration so far. I tried length +1, and just 100, all ending with same bad request.
Below is my code. Can you tell me what is the problem?
var options = {
hostname: hostname,
port: port,
headers: {
'Content-Type': 'application/json',
'Cache-Control': 'no-cache'
// 'Content-Length': post_data.length
}
};
describe('API Testing Function', function () {
db.bind('user');
describe('POST /api/user', function () {
it('should return 400 when password is not present', function (done) {
options.method = 'POST';
options.path = '/api/user';
var post_data = JSON.stringify({email:'111@email.com'});
options.headers['Content-Length'] = post_data.length; // error here
// if I delete above line, then it is totally good request.
var req = http.request(options, function(res){
res.on('data', function(chunk){
// console.log('BODY:' + chunk);
var result = JSON.parse(chunk);
assert.equal(400, result.code);
done();
});
});
req.write(post_data, 'utf8');
req.end();
});
});
});