如何从axios返回数据响应

时间:2020-06-04 04:25:14

标签: reactjs api axios

我有一个问题,当我调用波纹管代码之类的函数时,如何从axios返回响应数据以便访问

let free = true;
if (found === true && premium === 'active' || premium === 'trialing') {
   free = false 
}

我编写的脚本 dataJson 未定义

4 个答案:

答案 0 :(得分:0)

您可以通过这种形式使用Ecmascript 7的async / await实现此目的

您正在从此javascript文件(例如-test.js)中将此功能默认导出。

test.js

myTypes.js

main.js

import react,{useState} from 'react'
import axios from 'axios'

export default async function getAPI (v) {
    const res = await axios.post(v);
    return res.data;
}

无论何时需要/导入此文件,您都将获得此函数作为参考,您将调用该函数并捕获该函数返回的API响应

答案 1 :(得分:0)

您可以使用async / await轻松实现这一目标。

export default async function getAPI (v){
  var res = await axios.post(v)

  console.log(res.data)
  return res.data
}

或者,您可以传递一个回调函数,该函数可以从then部分中进行调用,如下所示

export default function getAPI (v, callbackFn){
  axios.post(v)
    .then((res)=>{
      dataJson =  res.data
      console.log(dataJson) // this would print response
      callbackFn(dataJson)
    })
}

答案 2 :(得分:0)

因此,您可以通过两种方法执行此操作:

1。)使用.then

import react,{useState} from 'react'
    import axios from 'axios'

    export default function getAPI (v){
        axios.post(v)
        .then((res)=>{
         console.log(dataJson)
            return res.data
        })
    }

2。)使用try catch

import react,{useState} from 'react'
    import axios from 'axios'

    export default function getAPI async(v){
      try{
        const res = await axios.post(v);
        return res.data
      }
      catch (error){
       return error
    }
  }

答案 3 :(得分:0)

dataJson是未定义的,因为您在then函数外部打印了它。 Axios是异步的,因此axios.postconsole.log将同时运行。

您可以使用async / await使其同步运行或在dataJson函数中打印then