Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"});

    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.

like image 224
umutm Avatar asked Feb 12 '13 15:02

umutm


2 Answers

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.

res.write(response.statusCode.toString());

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

like image 85
loganfsmyth Avatar answered Nov 19 '22 19:11

loganfsmyth


I get this error message and it mentions options.body

I had this originally

request.post({
    url: apiServerBaseUrl + '/v1/verify',
    body: {
        email: req.user.email
    }
});

I changed it to this:

request.post({
    url: apiServerBaseUrl + '/v1/verify',
    body: JSON.stringify({
        email: req.user.email
    })
});

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.post({
        url: apiServerBaseUrl + '/v1/verify',
        json: true,
        body: {
            email: req.user.email
        }
    });
like image 58
Alexander Mills Avatar answered Nov 19 '22 19:11

Alexander Mills