先请求再请求 axios

xeufq47z  于 2023-06-22  发布在  iOS
关注(0)|答案(1)|浏览(148)

如何简化这段代码?在请求服务器获取数据之前,我需要请求获取令牌。然后将此令牌写入localstorage,以免重新调用对令牌的请求。

if (localStorage.getItem('token')) {
  axios.defaults.headers.common["Authorization"] = localStorage.getItem("token");
  axios.post(`${BASE_URL}/json/em/pos/poses`, {
    limit,
    offset,
    contractType: 0,
    ...filter,
  })
    .then((res) => {
      dispatch(reducerGetOutlets({data: res.data, limit, offset: 0}));
    });
} else {
  axios(`${process.env.REACT_APP_BASE_URL}/api/user/info`)
    .then((response) => {
      axios.defaults.headers.common["Authorization"] = "Basic " + response.data.token;
      localStorage.setItem("token", "Basic " + response.data.token);
      axios.post(`${BASE_URL}/json/em/pos/poses`, {
        limit,
        offset,
        contractType: 0,
        ...filter,
      })
        .then((res) => {
          dispatch(reducerGetOutlets({data: res.data, limit, offset: 0}));
        });
    })
}
x759pob2

x759pob21#

你可以做一些事情来简化这段代码:
1.使用async/await语法进行API调用,而不是回调
1.将代码拆分为更小的函数。
例如:

async function getToken() {
  if (localStorage.getItem('token')) {
    return localStorage.getItem('token');
  } else {
    const response = await axios(`${process.env.REACT_APP_BASE_URL}/api/user/info`);
    const token = "Basic " + response.data.token;
    localStorage.setItem('token', token);
    return token;
  }
}

async function fetchData() {
  const token = await getToken();
  axios.defaults.headers.common["Authorization"] = token;
  const response = await axios.post(`${BASE_URL}/json/em/pos/poses`, {
    limit,
    offset,
    contractType: 0,
    ...filter,
  });
  dispatch(reducerGetOutlets({ data: response.data, limit, offset: 0 }));
}

fetchData();

在这里你得到两个函数:getToken()fetchData()
getToken()函数检查令牌是否在localStorage中,如果不是,则请求获取令牌并将其写入localStorage
fetchData()函数等待来自getToken()的令牌,设置Authorization报头并发出请求。
希望这能帮上忙。

相关问题