首页 > 解决方案 > JS 从 http.get 分配 var

问题描述

试图将 json 数据分配给全局 js 变量...为什么这不起作用...尝试使用 fetch 并且当 console.log 向全局变量显示任何帮助时,此 http.get 一直未定义全局变量?


var https=require('https');
var testUrl="https://tools.learningcontainer.com/sample-json.json"
var firstName=""
var lastName=""
var age=0
function getNews(url1) {
var request = https.get(url1, function(response) {
    // console.log(response.statusCode); // for testing to see the status code
    var body = ''; // start with an empty body since node gets responses in chunks

    // Read the data
    response.on('data', function(chunk) {
    body += chunk;
             });
    
    response.on('end', function() {
    if ( response.statusCode === 200 ) {
       data=JSON.parse(body)
       //console.log(data)
        }
       assignData(data)  
    })
})
}

function assignData(data) { // function to process data
firstName=data.firstName
lastName=data.lastName
age=data.age
console.log(firstName,lastName,age)
}
    
getNews(testUrl);
console.log(firstName,lastName,age)

标签: javascriptnode.js

解决方案


您必须等到所有数据都已收到并处理完毕。

您可以使用例如“等待/异步”...

出于演示目的,我在最后设置了一个简单的超时。

    var https = require('https');
    var testUrl = "https://tools.learningcontainer.com/sample-json.json"
    var firstName = ""
    var lastName = ""
    var age = 0
    function getNews(url1) {
        var request = https.get(url1, function (response) {
            // console.log(response.statusCode); // for testing to see the status code
            var body = ''; // start with an empty body since node gets responses in chunks
    
            // Read the data
            response.on('data', function (chunk) {
                body += chunk;
            });
    
            response.on('end', function () {
                if (response.statusCode === 200) {
                    data = JSON.parse(body)
                    //console.log('[response]',data)
                }
                assignData(data)
            })
        })
    }
    
    function assignData(data) { // function to process data
        firstName = data.firstName
        lastName = data.lastName
        age = data.age
        console.log('[assignData]', firstName, lastName, age)
    }
    
    getNews(testUrl);
    
console.log('[resultToEarly]', firstName, lastName, age)

setTimeout(function() {
    console.log('[resultAfterWaiting]', firstName, lastName, age)
    }, 3000);

推荐阅读