javascript - 从链接加载 JSON 以在范围内使用

标签 javascript node.js express

我在 express 中使用请求模块从链接加载 json。

var url = 'https://api.github.com/users/google/repos';

request.get({
    url: url,
    json: true,
    headers: {'User-Agent': 'request'}
}, (err, res, data) => {
    if (err) {
        console.log('Error:', err);
    } else if (res.statusCode !== 200) {
    console.log('Status:', res.statusCode);
} else {
    // data is already parsed as JSON:
    console.log(data.length);
}
});

console.log 的输出返回长度为 30。

我如何在函数外部全局使用已解析的 JSON(数据)?如果我在外面使用 console.log(data.length)

Cannot read property 'length' of undefined

谢谢!

最佳答案

你可以这样做

function AnyFunction(res){
//do what you want here 
console.log(res.length);
}

const options = {
  method: 'GET',
  uri: 'https://api.github.com/users/google/repos',
  json: true,
  headers: {'User-Agent': 'request'}
}
​
request(options)
  .then(function (response) {
    // Request was successful, use the response object at will
    console.log(response.length);
   //you can also pass it in a function and do whatever you want
   AnyFunction(response);
  })
  .catch(function (err) {
    // Something bad happened, handle the error
    console.log('Error:', err);
  })

关于javascript - 从链接加载 JSON 以在范围内使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48462142/

相关文章:

javascript - 通过移动左边缘来调整谷歌地图的大小

javascript - jQuery的remove()函数会取消元素的请求吗

javascript - 模态消息作为 javascript 警报?

node.js - 如何向 Electron 生成器注册.dll

javascript - 在 Node js 中创建文本文件时出现错误 : ENOENT: no such file or directory, 打开错误

node.js - 如何限制express api仅允许来自您的客户端的post请求?

node.js - 使用expressjs multer时xhr上传进度

javascript - 如何放大饼图并移动到中心

javascript - 在 koa-session 数据库实例上的 get/set/destroy 方法中放置什么?

javascript - 静态资源加载失败