我有一个问题,当我尝试运行一个简单的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);
}
}
);
我该如何解决这个问题?
最佳答案
我建议您使用标准的内置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
关于javascript - HttpRequest Node.js“无法设置未定义的属性'UNSENT'”,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41524465/