如何在 API 调用中使用 axios 在 React 中使用异步等待 [英] How to use async await in React using the axios in the API call

查看:87
本文介绍了如何在 API 调用中使用 axios 在 React 中使用异步等待的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Web 开发的新手.我正在使用 react.js.所以,在这里我想使用 async/await 进行 API 调用.我正在使用 axios.

I am new to the web development. I am using react.js.So, Here I want to use the async/awaitfor the API call. I am using axios.

现在

我所拥有的就像

export function fetchToken(bodyjson) {
  return (dispatch) => {
    let url = LOGIN_PATH + "username=" + bodyjson.userName + "&password" + "=" + bodyjson.password;
    return post(url, bodyjson)
      .then((response) => {
        if (response.status === 200) {
          localStorage.setItem('user', bodyjson.userName);
          localStorage.setItem('access_token', response.payload.access_token);
          history.push('/');
          dispatch({
            type: LOGIN_SUCCESS,
            data: response.payload,
          })
        }
        else {
          dispatch({
            type: LOGIN_FAILED,
            data: response.status,
          });
        }
      })
  }
}

我的邮政服务就像,

export const post = (url, post_data) =>
    axios.post(
        apiGatewayEndpoint.apiGatewayEndpoint + url,
        post_data,
        {
            headers: {
                "Authorization": localStorage.getItem("access_token") !== null ? `Bearer ` + localStorage.getItem("access_token") : null,
                "Content-Type": "application/json"
            }
        }
    ).then(data => {
        if (data.status === HttpStatus.OK) {
            return {
                status: data.status,
                payload: data.data
            };
        }
    }).catch(err => {
        return {
            status: err.response.data,
            payload: null
        };
    });

现在,我想在这里使用异步等待.我在这之间很困惑.我经历了很多教程.我想在 login 后立即调用 API.在此基础上,我想将用户重定向到差异页面.

Now, I want to use the async await over here. I am very confused between this. I have gone through lots of the tutorials. I want to call an API immediately after the login. on that basis I want to redirect user to the diff pages.

那么,谁能帮我解决这个async-await

So, can any one help me with this async-await

谢谢:-)

现在我正在使用它,

export function fetchToken(bodyjson) {
  return async (dispatch) => {
    let url = LOGIN_PATH + "username=" + bodyjson.userName + "&password" + "=" + bodyjson.password;
    let response = await post(url, bodyjson)
    if (response.status === 200) {
      localStorage.setItem('user', bodyjson.userName);
      localStorage.setItem('access_token', response.payload.access_token);
      let fetchJd = FETCH_JD_ROOT_URL + page + "&" + size;
      let newApiResponse = await get(fetchJd)
      if (newApiResponse.status === 200) {
        dispatch({
          type: LOGIN_SUCCESS,
          data: response.payload,
        })
        dispatch(sendUserJd(newApiResponse.payload));
      }else {
    dispatch({
      type: LOGIN_FAILED,
      data: response.status,
    });
  }

    }
    else {
      dispatch({
        type: LOGIN_FAILED,
        data: response.status,
      });
    }
  }

推荐答案

对于get请求,可以使用params发送数据等

for get requests, you can use params to send data etc etc.

   export const getData = async () => {
    try {
        const { data } = await axios({
            method: 'get', //you can set what request you want to be
            url: `yoururl`,
            params: {
            // key values pairs   
            }
            headers: {
                'token': token
            }
        });
        // run some validation before returning
        return data;
    } catch (e) {
        console.log(e);
        return .. some error object;
    }
};

用于发布请求

export const getData = async (params) => {
    try {
        const { data } = await axios({
            method: 'post', //you can set what request you want to be
            url: `url`,
            data: params,
            headers: {
                'x-auth-Token': token
            }
        });
        // run some validation before returning
        return data;
    } catch (e) {
        console.log(e);
        return .. some error object;
    }
};

错误对象示例

{
  status: 'error',
  message: 'failed with something'
}

然后你可以像这样调用任何api,

then you can call any api like this,

async componentDidMount() {
 const data = await getData();
 if(data.status === 'Something') {
// do something    
  }
}

这篇关于如何在 API 调用中使用 axios 在 React 中使用异步等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆