如何在节点中的获取请求内达到一个值?

时间:2019-01-29 19:36:54

标签: javascript node.js http-get

我无法在https.get()请求中达到一个值。
例如,parsedData.competition.id将在控制台中显示竞赛编号(2021),但不会将值添加到变量foo中。我的猜测是,在json对象准备好之后,get请求就会调用,对吗?所以我的问题是:所以我的问题是:我如何达到该值,然后将其添加到Test json对象,应该导出什么?

/**
 * This file uses the NodeJS --experimental-modules
 * flag, with the .mjs-extension
 */

// Dependencies
import https from 'https'

// Test variable
var foo

// GET request options
const httpsGetOptions = {
    hostname: 'api.football-data.org',
    port: 443,
    path: '/v2/competitions/2021/standings',
    headers: {
        'Content-Type': 'application/json',
        'X-Auth-Token': 'API_KEY'
    }
}

// GET request
https.get(httpsGetOptions, (res) => {
    const { statusCode } = res
    const contentType = res.headers['content-type']
    console.log(contentType)
    let error

    if (statusCode !== 200)
        error = new Error(`Request Failed.\nStatus Code: ${statusCode}`)
    else if (!/^application\/json/.test(contentType))
        error = new Error(`Invalid content-type.\nExpected application/json but received ${contentType}`)

    if (error) {
        console.error(error.message)
        res.resume() // consume response data to free up memory
        return
    }

    res.setEncoding('utf8')
    let rawData = ''
    res.on('data', (chunk) => { rawData += chunk })
    res.on('end', () => {
        try {
            const parsedData = JSON.parse(rawData)
            console.log(parsedData.competition.id)
            foo = paresedData.competition.id
        } catch (e) {
            console.error(e.message)
        }
    })
}).on('error', (e) => {
    console.error(`Got error: ${e.message}`)
})

// Create a Json object that can be exported
const Test = {
    "name": "Test",
    "id": foo
}
export default Test

0 个答案:

没有答案