Nodejs: response.write() for https.request?



嗨,我正在尝试向 API 服务器https.request。我可以接收块并在控制台中打印它。如何将其直接写入 html 并在浏览器中显示?

我试图寻找相当于response.write() http.request,但没有找到。 res.write(chunk)会给我一个TypeError.我该怎么做?

var req = https.request(options_places, function(res){
  console.log('STATUS: ' + res.statusCode);
  console.log('HEADERS: ' + JSON.stringify(res.headers));
  res.setEncoding('utf8');
  res.on('data', function(chunk){
       console.log('BODY: ' + chunk); // Console can show chunk data
       res.write(chunk); // This gives TypeError: Object #<IncomingMessage> has no method 'write'
  });
});
req.end();
req.on('error', function(e){
  console.log('ERROR?: ' + e.message );
});

首先,您必须创建服务器并在某个端口上侦听请求。

var http = require('http');
http.createServer(function (request, response) {
    response.writeHead(200, {'Content-Type': 'text/plain'});
    response.end('Whatever you wish to send n');
}).listen(3000); // any free port no.
console.log('Server started');

现在它侦听 127.0.0.1:3000 的传入连接

对于特定的网址,请使用.listen(3000,'your url')而不是listen(3000)

这对

我有用。

app.get('/',function(req, res){ // Browser's GET request
  var options = {
       hostname: 'foo',
       path: 'bar',
       method: 'GET'
    };
  var clientRequest = https.request(options, function(clientResponse){
    console.log('STATUS: ' + res.statusCode);
    console.log('HEADERS: ' + JSON.stringify(res.headers));
    clientResponse.setEncoding('utf8');
    clientResponse.on('data', function(chunk){
         console.log('BODY: ' + chunk);
         res.write(chunk); // This respond to browser's GET request and write the data into html.
     });
  });
 clientRequest.end();
 clientRequest.on('error', function(e){
    console.log('ERROR: ' + e.message );
  });
});

最新更新