请求之前的另一个请求 axios

huangapple go评论70阅读模式
英文:

request before another request axios

问题

如果要简化这段代码,可以尝试以下方式:

const getToken = async () => {
  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;
  }
};

const fetchData = async () => {
  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函数,它在获取令牌后设置请求头,并发起数据请求。这种方式更清晰和模块化,可以减少重复的代码块。

英文:

How can i simplify this code? I need to make a request to get the token, before requesting the server to get the data. Then write this token to localstorage so as not to re-call a request for a token.

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}));
        });
    })
}

答案1

得分: 1

以下是已翻译的内容:

你可以采取一些方法来简化这段代码:

  1. 在API调用中使用async/await语法,而不是回调函数。
  2. 将代码拆分为较小的函数。

例如:

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头并发出请求。

希望这有所帮助。

英文:

You could do a couple things to simplify this code:

  1. Use async/await syntax for your API calls instead of callbacks
  2. Split your code into smaller functions.

For example:

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();

Here you get two functions: getToken() and fetchData().

getToken() function checks if the token is in the localStorage and if not it makes a request to get the token and writes it to localStorage.

fetchData() function awaits the token from getToken(), sets the Authorization header and makes the request.

Hope this helps.

huangapple
  • 本文由 发表于 2023年6月9日 03:50:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/76435266.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定