javascript node.js - XMLHttpRequest,获取头信息

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25652057/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 04:48:15  来源:igfitidea点击:

node.js - XMLHttpRequest, get header informations

javascriptnode.jsxmlhttprequest

提问by jan

I want to get the headers of the website "http://facebook.com". This should be a 302 Moved Permanently and I want to call the referred link which is provided in the response header.

我想获取网站“ http://facebook.com”的标题。这应该是一个 302 Moved Permanently,我想调用响应头中提供的引用链接。

Here is my code:

这是我的代码:

var req = new XMLHttpRequest();
req.open('GET', "http://facebook.com/", false);
req.send(null);
var headers = req.getAllResponseHeaders().toLowerCase();
console.log(headers);

And here is the error message:

这是错误消息:

/home/node_modules/xmlhttprequest/lib/XMLHttpRequest.js:230
for (var i in response.headers) {

TypeError: Cannot read property 'headers' of undefined
    at getAllResponseHeaders (/home/node_modules/xmlhttprequest/lib/XMLHttpRequest.js:230:27)
    at Object.<anonymous> (/home/browse/init.js:67:19)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Function.Module.runMain (module.js:497:10)
    at startup (node.js:119:16)
    at node.js:906:3

I hope you can help me.

我希望你能帮助我。

回答by sachaamm

If you want to use xmlHttpRequest with Node js you have to install required package.

如果你想在 Node js 中使用 xmlHttpRequest,你必须安装所需的包。

First, write this line in a console:

首先,在控制台中写下这一行:

npm install xmlhttprequest

Then, when you write a .js file on your server , you have to indicate first

然后,当你在你的服务器上写一个 .js 文件时,你必须先表明

var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var xhr = new XMLHttpRequest();

回答by sarbbottam

The following code should be sufficient, as per the comment, you don't need XHR.

以下代码应该足够了,根据评论,您不需要XHR.

var http = require('http');

var options = {
  hostname: 'www.google.com',
  port: 80,
  method: 'GET'
};

var req = http.request(options, function(res) {
  console.log('headers:\n' + JSON.stringify(res.headers));
  res.setEncoding('utf8');
  res.on('data', function (chunk) {
    console.log('body:\n' + chunk);
  });
});

req.on('error', function(e) {
  console.log('problem with request: ' + e.message);
});
req.end();