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

时间:2015-04-10 18:33:55

标签: node.js

您好我正在尝试向{+ 1}} API服务器。我可以收到块并在控制台中打印它。如何将其直接写入html并在浏览器中显示?

我试图寻找相当于https.request的{​​{1}}但未找到的response.write()http.request会给我一个res.write(chunk)。我怎样才能做到这一点?

TypeError

3 个答案:

答案 0 :(得分:2)

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

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,'您的网址')而非收听(3000)

答案 1 :(得分:0)

这对我有用。

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

});

答案 2 :(得分:0)

const https = require('https');

https.get('https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY', (resp) => {
  let data = '';

  // A chunk of data has been recieved.
  resp.on('data', (chunk) => {
    data += chunk;
  });

  // The whole response has been received. Print out the result.
  resp.on('end', () => {
    console.log(JSON.parse(data).explanation);
  });

}).on("error", (err) => {
  console.log("Error: " + err.message);
});