簡體   English   中英

如何從NodeJS的https獲取正文?

[英]How to get body text from NodeJS' https?

在 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>

下面給了我這個堆棧跟蹤,但我沒有看到statusText或任何可能包含curl輸出的文本的相關內容。 res.statusCode有效,但res.statusText 我什至沒有看到res.response ...

const https = require('https')

const options = {
  hostname: 'encrypted.google.com',
  port: 443,
  path: '/',
  method: 'GET',
};
options.agent = new https.Agent(options);

const req = https.request(options, (res) => {
  console.log(res)
});

req.on('error', (e) => {
  console.error(e);
});

req.end();

更新:也捕獲響應正文。

您可以使用res.statusMessage獲取狀態文本,使用res.statusCode獲取狀態代碼。 並且,您可以捕獲偵聽data事件的響應主體。

干得好:

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>

在此處查看響應對象的官方文檔https://nodejs.org/api/http.html#http_class_http_serverresponse

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM