gpt4 book ai didi

javascript - HttpRequest Node.js "Cannot set property ' UNSENT' 未定义”

转载 作者:行者123 更新时间:2023-11-28 05:09:07 28 4
gpt4 key购买 nike

我有一个问题,当我尝试运行简单的 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 "Cannot set property ' UNSENT' 未定义”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41524465/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com