繁体   English   中英

将 api fetch 更改为 axios 调用

[英]change api fetch into axios call

我正在尝试将 api 获取更改为 axios 获取方法我不知道该怎么做

 const fetchApi = () => {
    const request = getAllActivityData();

    request
      .api({
        params: {
          customer,
        },
      })



我想使用 axios 像这样调用 api

我已在代码框中添加了完整代码,如果您可以编辑代码框并使其正常工作,将会很有帮助


 useEffect(() => {
    const config = {
      headers: {
        Authorization: `token  
      },
    };

    axios.get("customer/get-all-activity-data/?customer=22", config)
.then((res) => {
      console.log(res.data);
     
    });

代码沙箱

https://codesandbox.io/s/upbeat-jasper-2jmri?file=/src/App.js:3137-3298

我尝试过的数据未显示,但没有错误。 我在 postman 中获取数据

https://codesandbox.io/s/gifted-montalcini-j7nv7?file=/src/App.js

你的意思是这样的,使用异步等待......

const axiosCallFn = async () => {
  let url = '...'
  let config = {
    headers: {
      token: '...'
    }
  }

  try {
    let resp = await axios.get(url, config)
    return resp.data  
  } catch(e) {
    throw e
  }
}

// import the function into your component and use it like so
axiosCallFn()
  .then((data) => {
    // your functionality here.
  })
  .catch(() => {
    // your error functionality here.
  })

然后你可以在你的useEffect中调用你的axiosCallFn。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM