【问题标题】:how to return response of axios in return如何返回axios的响应作为回报
【发布时间】:2018-01-19 02:45:47
【问题描述】:

我想返回 axios 的响应,但返回的响应总是未定义:

wallet.registerUser=function(data){
axios.post('http://localhost:8080/register',{
phone:data.phone,
password:data.password,
email:data.email
}).then(response =>{
  return response.data.message;
  console.log(response.data.message);
}).catch(err =>{
  console.log(err);
})
}

console.log(wallet.registerUser(data));

控制台始终记录为未定义。他们是否会以任何方式返回此响应。

【问题讨论】:

  • 注意:返回后不能console.log。这就是所谓的无法访问的代码——它永远无法执行。
  • 它返回未定义,因为您没有成功调用您认为的任何端点。通过在邮递员中运行它来检查 URL。您可能需要添加一些标头,并且可能还需要禁用证书检查。如果您的环境需要代理,则 axios 将无法工作。请参阅下面的答案。

标签: reactjs axios


【解决方案1】:

console.log 在记录之前不会等待函数完全完成。这意味着您必须使 wallet.registerUser 异步,有两种主要方法可以做到这一点:

  1. 回调 - 这是当您将函数作为参数传递给现有函数时,该函数将在您的 axios 调用完成后执行。以下是它如何与您的代码一起使用:

    wallet.registerUser=function(data, callback){
      axios.post('http://localhost:8080/register',{
        phone:data.phone,
        password:data.password,
        email:data.email
      }).then(response =>{
        callback(response.data.message);
        console.log(response.data.message);
      }).catch(err =>{
        console.log(err);
      })
    }
    
    wallet.registerUser(data, function(response) {
      console.log(response)
    });
    
  2. 承诺 - 最简单的方法是将async 放在函数名前面。这将使函数返回的任何内容都以 Promise 的形式返回。这就是它在您的代码中的工作方式:

     wallet.registerUser=async function(data){
      axios.post('http://localhost:8080/register',{
        phone:data.phone,
        password:data.password,
        email:data.email
      }).then(response =>{
        return response.data.message;
        console.log(response.data.message);
      }).catch(err =>{
        console.log(err);
      })
    }
    
    wallet.registerUser(data).then(function(response) {
      console.log(response);
    });
    

这里是关于异步函数的更多信息:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

https://developer.mozilla.org/en-US/docs/Glossary/Callback_function

【讨论】:

  • 这是正确的。控制台是同步的,Axios 正在进行异步调用。
  • 上面的第二个例子不正确——你需要使用 await 来调用上面的第二个场景。
【解决方案2】:

你可以使用 Promises:

我是新来的反应,所以你可以给我建议以改进我的代码。

例如我想调用其他文件中的 checkVerified() 函数:

Utils.js

export function checkVerified(val, values) {
    return new Promise((resolve, reject) => {
        axios
            .get(`${getInitialServerUrl}/core/check_verified/${val}/`)
            .then(res => {
                resolve(res)
            })
            .catch(err => reject(err))
    })
}

我正在从另一个文件中调用此函数:

someFile.js

const handleSubmit = e => {
        e.preventDefault();
        checkVerified(values.mobile, props)
            .then(res => {
               console.log(res);
         })
        .catch(err => console.log(err.response))
    }

【讨论】:

    【解决方案3】:

    您需要将对 axios 的调用包装在异步函数中。然后,您可以像往常一样返回响应。

    只要用 await 调用包装器方法就可以了。 不幸的是,为了使用 await 调用它,调用方法也必须标记为 async,依此类推,直到应用程序中的每个函数都必须标记为 async,并且您需要使用 await 调用所有函数.

    这就是 async / await 关键字的魔力和美妙之处——完全是垃圾。您可能会看到创建异步 lambda 以包装 await axios 的示例,以尝试不必重构整个应用程序,但它不起作用。

    因此,包装器如下所示...

    异步公开帖子(URL,数据){

    axios.post(URL, data)
        .then( (result) => {
            return result;
        });
    

    }

    如果您使用的是 typescript,那会增加几个令人沮丧的问题,例如如何将 any 转换为您想要返回的类型。我可能会建议联合类型。

    无论如何,祝你好运!

    附:如果您的环境需要使用代理,axios 将无法工作。在这种情况下,可能还有其他所有情况,请使用 node-fetch - 您将在一天内启动并运行 node-fetch。一周后 Axios 会让你摸不着头脑,想知道它为什么不工作。

    【讨论】:

      【解决方案4】:

      这里的重点是访问承诺值。为此,我们只需要以以下格式记录响应。

      static getSearchAPI = () => {
      return axios.post(URl);
      }
      
      getRestaurents() {
      Helpers.getSearchAPI().then(function (response) {
        console.log(response.data);
      })}
      

      【讨论】:

      • 这个答案没有解决实际问题——即如何从 axios 调用返回响应。从语法上讲,这个答案也是不可用的。
      • 因为我们没有任何方法可以返回响应,所以我认为这个想法会有所帮助。这里我们可以使用一些全局变量来存储响应并使用它。
      • 全局变量也不是一个好主意。您确实有一种返回响应的方法 - 请参阅下面的答案。
      【解决方案5】:

      我会使用紧凑的语法来实现这样的 axios 调用:

        myAxiosCall = async () => {
          return await axios.get('/the-url');
        }

      可以这样调用:

      myAxiosCall.then(data) {
         // Process the axios response
      }
      

      【讨论】:

        【解决方案6】:

        我使用了 async 和 await 方法,并将我的 axios 调用和调用 axios 调用的函数包装在这些方法中。我返回了 axios 值以及其中返回的响应对象。我在下面的链接中分享了 sn-p。

        Returning data from Axios API

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-07-30
          • 1970-01-01
          • 2020-03-02
          • 2020-10-09
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多