Javascript 如何从NodeJS';https?

Javascript 如何从NodeJS';https?,javascript,node.js,ecmascript-6,Javascript,Node.js,Ecmascript 6,在NodeJS中使用https时,如何获取curl输出的文本 $ curl --max-redirs 0 encrypted.google.com <HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8"> <TITLE>301 Moved</TITLE></HEAD><BODY&

在NodeJS中使用
https
时,如何获取
curl
输出的文本

$ curl --max-redirs 0 encrypted.google.com

<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
<TITLE>301 Moved</TITLE></HEAD><BODY>
<H1>301 Moved</H1>
The document has moved
<A HREF="https://www.google.com/">here</A>.
</BODY></HTML>

更新:同时捕获响应主体。

您可以使用获取状态文本和状态代码。并且,您可以捕获侦听
数据的响应主体

给你:

const req = https.request(options, (res) => {
  console.log('Status code:', res.statusCode);
  console.log('Status text:', res.statusMessage);

  let body = '';

  res.on('data', (data) => {
    body += data.toString();
  });

  res.on('end', () => {
    console.log('Response body:');
    console.log(body);
  });
});
输出:

Status code: 301
Status text: Moved Permanently
Response body:
<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
<TITLE>301 Moved</TITLE></HEAD><BODY>
<H1>301 Moved</H1>
The document has moved
<A HREF="https://www.google.com/">here</A>.
</BODY></HTML>

状态代码:301
状态文本:永久移动
答复机构:
301移动
301移动
文档已移动
.

检查此处响应对象的正式文档

您需要在
请求
回调中设置一个,输出任何状态文本的curl在哪里?这看起来非常像一个普通的HTTP主体。使用
res.statusMessage
@PatrickEvans这就是解决方案。如果你把它贴出来,我会把它标记为答案。
Status code: 301
Status text: Moved Permanently
Response body:
<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
<TITLE>301 Moved</TITLE></HEAD><BODY>
<H1>301 Moved</H1>
The document has moved
<A HREF="https://www.google.com/">here</A>.
</BODY></HTML>