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



我正在尝试访问Microsoft Azure Management API,我已经到了可以控制台.log((来自axios调用的数据的地步。

我不知道该怎么做,就是如何将axios调用封装在函数中,然后在以后检索数据?

我的代码在下面。请注意,我在控制台中看到了从MSapi返回的数据,正如我所期望的那样。


// 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)
})

有人能伸出援手吗?

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

// 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)
})

最新更新