如何在Node.js中获取响应头的值

时间:2019-02-06 08:22:43

标签: javascript node.js

const URL = 'https://www.imdb.com/title/tt0816222/? 
ref_ = fn_al_tt_2 ';

(async() => {

    const response = await request({
      uri: URL,
      headers: {
        'Connection': 'keep-alive',
        'User-Agent': 'Mozilla/0.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36'

      },

    });

我需要此代码的帮助。如何在以下站点的Visual Studio代码控制台中获取响应标头值。

5 个答案:

答案 0 :(得分:1)

只需处理request库中的Promise

  request({
    uri: 'https://www.imdb.com/title/tt0816222/?',
    headers: /*your headers*/ 
    })
    .then(function(response){
       console.log(response.headers)
    })

答案 1 :(得分:0)

您将在response.headers中获得响应头

答案 2 :(得分:0)

像这样打印

console.log(response.headers)

答案 3 :(得分:0)

此代码显示标题:

const URL = 'https://www.imdb.com/title/tt0816222/?ref_ = fn_al_tt_2';
const request = require('request');

(async () => {

  const response = await request({
    uri: URL,
    headers: {
      'Connection': 'keep-alive',
      'User-Agent': 'Mozilla/0.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36'

    },

  });
  console.log(response.headers);
})();

答案 4 :(得分:0)

因为您只是从请求npm中获取响应主体。

在请求选项中添加resolveWithFullResponse:true。

const URL = 'https://www.imdb.com/title/tt0816222/? 
ref_ = fn_al_tt_2 ';

(async() => {

    const response = await request({
      uri: URL,
      headers: {
        'Connection': 'keep-alive',
        'User-Agent': 'Mozilla/0.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36'

      },
	resolveWithFullResponse: true
    });

如果只需要标题

const URL = 'https://www.imdb.com/title/tt0816222/? 
ref_ = fn_al_tt_2 ';

(async() => {

    const {headers} = await request({
      uri: URL,
      headers: {
        'Connection': 'keep-alive',
        'User-Agent': 'Mozilla/0.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36'

      },
	resolveWithFullResponse: true
    });
    
    console.log(headers)