umutm umutm - 10 months ago 289
HTTP Question

nodejs - first argument must be a string or Buffer - when using response.write with http.request

I'm simply trying to create a node server that outputs the HTTP status of a given URL.

When I try to flush the response with res.write, I get the error: throw new TypeError('first argument must be a string or Buffer');

But if I replace them with console.log, everything is fine (but I need to write them to the browser not the console).

The code is

var server = http.createServer(function (req, res) {
res.writeHead(200, {"Content-Type": "text/plain"});

uri: '',
method: 'GET',
}, function(error, response, body) {
if (!error) {
} else {


I believe I should add a callback somewhere but pretty confused and any help is appreciated.


response.statusCode is a number, e.g. response.statusCode === 200, not '200'. As the error message says, write expects a string or Buffer object, so you must convert it.


You are also correct about your callback comment though. res.end(); should be inside the callback, just below your write calls.