HttpRequest Node.js“无法设置属性'UNSENT'未定义”

时间:2017-01-07 17:41:26

标签: javascript httprequest

我遇到了问题,当我尝试运行一个简单的http请求时,我总会收到一条错误消息。

无法设置未定义的属性“UNSENT”

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

XMLHttpRequest('https://example.firebaseio.com/.json',
   function (error, response, body) {
      if (!error && response.statusCode === 200) {
       console.log(body);        
     }
   }
);

如何解决此问题?

2 个答案:

答案 0 :(得分:0)

我建议你使用标准的内置NodeJS方法:

此代码:

var http = require('http');
http.get('http://nodejs.org/dist/index.json', (res) => {
  const statusCode = res.statusCode;
  const contentType = res.headers['content-type'];

  let error;
  if (statusCode !== 200) {
    error = new Error(`Request Failed.\n` +
                      `Status Code: ${statusCode}`);
  } else if (!/^application\/json/.test(contentType)) {
    error = new Error(`Invalid content-type.\n` +
                      `Expected application/json but received ${contentType}`);
  }
  if (error) {
    console.log(error.message);
    // consume response data to free up memory
    res.resume();
    return;
  }

  res.setEncoding('utf8');
  let rawData = '';
  res.on('data', (chunk) => rawData += chunk);
  res.on('end', () => {
    try {
      let parsedData = JSON.parse(rawData);
      console.log(parsedData);
    } catch (e) {
      console.log(e.message);
    }
  });
}).on('error', (e) => {
  console.log(`Got error: ${e.message}`);
});

取自here

答案 1 :(得分:0)

这将起作用。

    var req = new XMLHttpRequest()
    req.open('GET',url)

    req.onload = function(){
    if(req.status==200){
     console.log(req.responseText)
        }

    else{
     console.log(req.statusText)
       }
    }

    req.onerror = function()
    {
    console.log('Network Error')
    }

    req.send()
    })