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

前端 未结 8 1951
难免孤独
难免孤独 2020-12-24 11:29

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 T

8条回答
  •  南笙
    南笙 (楼主)
    2020-12-24 11:43

    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:

    var obj = { test : "test" };
    console.log( obj ); // works
    res.write( obj ); // fails
    

    One way to convert anything to string is to do that:

    res.write( "" + obj );
    

    whenever you are trying to send something. The other way is to call .toString() method:

    res.write( obj.toString( ) );
    

    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, then res.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:

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

提交回复
热议问题