如何在node.js中获取响应头

6
我正在处理一个nodejs项目,我使用request模块提交restful请求并获取响应。(这是该模块的链接:https://github.com/request/request
根据说明,我应该通过调用response.headers['']来获取响应头。然而,当我尝试调用var contentType = response.headers['Content-Type']时,contentTypeundefined。(当我使用postman时,我可以从响应中获取Content-Type)。有人知道出了什么问题吗?
这是网站上的说明:
var request = require('request')
request(
    { method: 'GET'
    , uri: 'http://www.google.com'
    , gzip: true
    }
  , function (error, response, body) {
      // body is the decompressed response body
      console.log('server encoded the data as: ' + (response.headers['content-encoding'] || 'identity'))
      console.log('the decoded data is: ' + body)
    }
1个回答

9
在Node中,标头使用小写名称来访问,因此使用response.headers['content-encoding']是正确的。
你的代码片段目前对我有效,显示“服务器将数据编码为:gzip。”

1
代码中写的是 content-encoding,而问题中写的是 content-type。只要使用小写字母,两者都可以使用。 - jeff carey

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接