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"});
request({
uri: 'http://www.google.com',
method: 'GET',
maxRedirects:3
}, function(error, response, body) {
if (!error) {
res.write(response.statusCode);
} else {
//response.end(error);
res.write(error);
}
});
res.end();
});
server.listen(9999);
I believe I should add a callback somewhere but pretty confused and any help is appreciated.
I get this error message and it mentions options.body
I had this originally
I changed it to this:
and it seems to work now without the error message...seems like bug though.
I think this is the more official way to do it:
Request takes a callback method, its async! So I am assuming, by the time the callback is executed the
res.end()
might get called. Try closing the request within the callback?!And there is another possibility (not in this case) when working with ajax(XMLhttpRequest), while sending information back to the client end you should use res.send(responsetext) instead of res.end(responsetext)
Well, obviously you are trying to send something which is not a string or buffer. :) It works with console, because console accepts anything. Simple example:
One way to convert anything to string is to do that:
whenever you are trying to send something. The other way is to call
.toString()
method:Note that it still might not be what you are looking for. You should always pass strings/buffers to
.write
without such tricks.As a side note: I assume that
request
is a asynchronous operation. If that's the case, thenres.end();
will be called before any writing, i.e. any writing will fail anyway ( because the connection will be closed at that point ). Move that line into the handler:if u want to write a JSON object to the response then change the header content type to application/json
response.statusCode
is a number, e.g.response.statusCode === 200
, not'200'
. As the error message says,write
expects astring
orBuffer
object, so you must convert it.You are also correct about your callback comment though.
res.end();
should be inside the callback, just below yourwrite
calls.