Node.js编写http请求响应

Node.js write http request response

本文关键字:请求 响应 http 编写 js Node      更新时间:2023-09-26

我正在使用此代码向自己的服务器发出HTTP请求。我在chunk中得到了适当的响应。

http.createServer(function (req, res) {
    var options = {
                    host: '<my ip>',
                    port: 8080,
                    method: 'GET',
                    path: '/content?data='+somedata
                };
    var call = http.request(options, function(res){
        res.setEncoding('utf8');                
        res.on('data', function(chunk){
            console.log("got response"+chunk);
        });
    }).on("error", function(e){
        console.log("Got error: " + e.message);
    });
    call.end();
}).listen(3000);

我的问题是如何将这个区块打印到我的浏览器?

将两个res变量中的一个更改为具有不同的名称。目前,对您请求的响应掩盖了您试图做出的响应。

然后:

response.write(chunk);

另请参阅:https://nodejs.org/api/http.html#http_response_write_chunk_encoding_callback

res.write(chunk);

也不要忘记结束第一次调用,这样浏览器就会知道请求已经结束。

res.end("success");