首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >无法访问函数外部的axios返回的数据。

无法访问函数外部的axios返回的数据。
EN

Stack Overflow用户
提问于 2021-07-22 13:36:57
回答 1查看 122关注 0票数 0

我正在尝试访问,我已经到了可以从axios调用中console.log()数据的地步。

我不知道该如何做,如何将我的axios调用封装在一个函数中,然后再检索数据呢?

我的密码在下面。注意,我在控制台中看到了从MS返回的数据,就像我预期的那样。

代码语言:javascript
复制
// Express setup code, module imports, env variables, etc.
// ...

function getAzureToken() {

    // Set up credentials, auth url and request body, axios config
    // The API authenticates properly, so it is not relevant to include
    // ...

    var data = {};
    axios.post(authEndpoint, config)
        .then(result => {
            console.log(result.data) // Logs the expected data (auth token) in my console
            data = result.data
        })
    
    return data 
}

// Index API endpoint
app.get('/', (req, res) => {

    let token = getAzureToken()

    // Prints out this in my browser: {}
    res.send(token)

})

有人能伸出援助之手吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-07-22 13:38:26

您需要在.then方法中返回以提取值。

代码语言:javascript
复制
// Express setup code, module imports, env variables, etc.
// ...

async function getAzureToken() {

    // Set up credentials, auth url and request body, axios config
    // The API authenticates properly, so it is relevant to include
    // ...

    return await axios.post(authEndpoint, config)
        .then(result => {
            console.log(result.data) // Logs the expected data (auth token) in my console
            return result.data
        })
}

// Index API endpoint
app.get('/', async (req, res) => {

    let token = await getAzureToken()

    // Prints out this in my browser: {}
    res.send(token)

})
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68485833

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档