问题描述
我遇到了一个我认为的小问题,但我找不到解决方法.我想使用 Node.js HTTPS GET 请求在变量中加载远程 JSON.这是成功的,但我不能在我的代码中的任何其他地方使用它.我的功能如下(来自 Node.js 文档):
I'm stuck with a small problem I think, but I can't find a way to solve it.I want to load a remote JSON in a variable, using Node.js HTTPS GET request. It's a success, but I can't use it anywhere else in my code. My function is the following (from Node.js doc):
function getMyFile() {
var https = require('https');
https.get('URL_I_am_targeting/file.json', (res) => {
var { statusCode } = res;
var contentType = res.headers['content-type'];
let error;
if (statusCode !== 200) {
error = new Error('Request Failed.
' +
`Status Code: ${statusCode}`);
} else if (!/^application/json/.test(contentType)) {
error = new Error('Invalid content-type.
' +
`Expected application/json but received ${contentType}`);
}
if (error) {
console.error(error.message);
// consume response data to free up memory
res.resume();
}
res.setEncoding('utf8');
let rawData = '';
res.on('data', (chunk) => {
rawData += chunk;
});
res.on('end', () => {
try {
const parsedData = JSON.parse(rawData);
console.log(parsedData);
} catch (e) {
console.error(e.message);
}
});
}).on('error', (e) => {
console.error(`Got error: ${e.message}`);
});
}
请求工作正常,因为我能够在控制台中正确记录我的 .json.但我的问题是我不能在我的代码中的任何其他地方使用常量parsedData".我试着写我的
The request works fine, as I am able to log my .json in the console correctly. But my problem is that I can't use the constant "parsedData" anywhere else in my code. I tried to write my
return parsedData;
在我的函数中的几个地方,但是当我在我的代码中使用该函数并尝试 f.e.
at several places in my function, but when I use the function in my code and try f. e.
var fileContent = getMyFile();
console.log(fileContent);
文件内容未定义.就像parsedData出不了请求一样.没有记录错误,请求正常,但我无法使用其中的内容.
fileContent is undefined. It's like parsedData can't go out of the request. There is no error logged, the request goes fine, but I just can't use the content out of it.
我不是 Javascript 专业人士,这可能是我从该请求返回值时出错的原因.
I am not a Javascript professional, and it's probably something I get wrong with returning value from this request.
如果有人知道我错在哪里以及什么可以解决问题,我们将不胜感激!谢谢!
If somebody knows where I'm wrong and what could do the trick, it will be greatly appreciated !Thanks !
推荐答案
你可以为你的函数编写一个基于 Promise 的包装器:
You could write a promise-based wrapper for your function:
function getMyFile() {
var https = require('https');
return new Promise((resolve, reject) => {
https.get('URL_I_am_targeting/file.json', (res) => {
var { statusCode } = res;
var contentType = res.headers['content-type'];
let error;
if (statusCode !== 200) {
error = new Error('Request Failed.
' +
`Status Code: ${statusCode}`);
} else if (!/^application/json/.test(contentType)) {
error = new Error('Invalid content-type.
' +
`Expected application/json but received ${contentType}`);
}
if (error) {
console.error(error.message);
// consume response data to free up memory
res.resume();
}
res.setEncoding('utf8');
let rawData = '';
res.on('data', (chunk) => {
rawData += chunk;
});
res.on('end', () => {
try {
const parsedData = JSON.parse(rawData);
resolve(parsedData);
} catch (e) {
reject(e.message);
}
});
}).on('error', (e) => {
reject(`Got error: ${e.message}`);
});
});
}
这样,你就可以像这样使用这个函数:
So that, you can use the function like this:
getMyFile()
.then(response => {
// handle success response here
})
.catch(error => {
// handle error here
});
这篇关于HTTPS GET请求使用结果【Node.js】的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!