【问题标题】:Axios returns undefined in separate functionAxios 在单独的函数中返回未定义
【发布时间】:2020-02-26 22:13:49
【问题描述】:

大家早上好!我在从其他函数获取 axios 响应时遇到问题。 具体来说,我正在咨询我在另一个网站上创建的服务,并让它返回一个数据库名称。 目前,当我直接使用 Postman 上的标头调用 api 时,它可以工作,并且在我使用 axios 创建的 getDbName() 函数内完成时也是如此,但是当我尝试将该响应返回到另一个响应时,它会打印出“未定义”。我的理解是,只要使用 response => 箭头函数,调用就会正确地等待响应。我的假设错了吗?

我已经尝试了许多不同的返回变量的尝试。我使用下面 SO 上的许多链接进行了调查,但仍然无法正常工作:

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.logs 的输出都应该是 dbn(数据库名称)。目前,一个返回正确的名称,另一个返回 undefined。

【问题讨论】:

标签: javascript node.js http axios backend


【解决方案1】:
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

});

【讨论】:

  • 嗨天使,我将其更改为使用解析和拒绝返回新的承诺,但路由函数的结果是相同的。它仍然在 getDbName 函数之外记录 undefined。
  • 我相信这会起作用,除非你犯了其他类型的错误。只要你的函数返回一些东西,它就会把结果带到你的 API 中。
【解决方案2】:

我是个白痴,忘记导出 getDbName 以便路由读取它。我有它被导入,但它没有从 [controller.js] 导出。我发布的代码运行良好。

【讨论】:

    猜你喜欢
    • 2021-12-29
    • 2020-10-24
    • 1970-01-01
    • 1970-01-01
    • 2017-10-31
    • 2021-07-07
    • 2020-10-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多