Node.js:response.write()为https.request?

嗨,我正在尝试做一个API服务器的https.request 。 我可以收到大块并在控制台中打印。 我怎样才能直接写入HTML并在浏览器中显示?

我试图寻找相当于http.requestresponse.write() ,但没有find一个。 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 ); }); 

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

 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的传入连接

对于特定的url使用.listen(3000,'你的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 ); }); });