大家早上好!我在从不同的函数获取 axios 响应时遇到问题。 具体来说,我正在咨询我在另一个网站中创建的服务并让它返回数据库名称。 目前,当我直接使用 Postman 上的 header 调用 api 时,它的工作原理与在我使用 axios 创建的 getDbName() 函数内完成时相同,但是当我尝试将该响应返回到另一个响应时,它会打印出“未定义” ”。据我了解,只要使用response =>箭头函数,调用就会正确等待响应。我的这个假设错了吗?
我尝试了许多不同的返回变量的尝试。我使用下面的许多链接进行了调查,但我仍然无法让它工作:
axios promise returns correct value in "axios.all" function, but is undefined in the "then" function
Axios prints value on console but returns undefined
GET request with axios returning undefined
[dbController.js]
import axios from 'axios';
import apiconfig from '../config/apiconfig';
function getDbName() {
return axios({
method: 'GET',
url: `${apiconfig.cb_url}/api/DbToBeWorked`,
headers: apiconfig.optionsHeaders,
}).then(dbn => {
console.log(dbn.data.db); //logs database name correctly
return dbn.data.db;
});
};
[routes.js]
import { Router } from 'express';
const routes = new Router();
routes.get('/api/test', (req, res) => {
getDbName().then(dbn => {
console.log(dbn) //this logs 'undefined'
return res.status(200).json(dbn);
});
});
两个 console.log 的输出都应为 dbn(数据库名称)。目前,一个返回正确的名称,另一个返回未定义的名称。
最佳答案
const getDbName = function () {
return new Promise((resolve, reject) => {
axios({
///----
})
.then(response => {
resolve({
// Do something
})
})
.catch(err => {
reject({
// Do something
})
})
})
}
routes.get('/api/test', async(req, res) => {
try{
await getDbName()
}catch(error)
/// error
});
关于javascript - Axios 在单独的函数中返回未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58645259/