开发者问题收集

我想将 axios.post 请求保存在 const 中并在函数中返回该 const

2022-12-24
743
export async function getCategories() {
  const https = "xxxxxx";
  const url = `${https}/api/Category/GetCategories`;

  const userToken ="xxxxxxxx"

  const authStr = "Bearer ".concat(userToken);

  const options = {
    method: "POST",
    headers: {
      Authorization: authStr,
    },
    url: url,
  };

  const response = await axios(options)
    .then((response) => console.log(response.data[0].categoryName))
    .catch((error) => console.log(error.toJSON()));

  const fetchedCategories = response.data[0];
  console.log(
    "🚀 ~ file: menu.js:27 ~ getCategories ~ fetchedCategories",
    fetchedCategories
  );

  return fetchedCategories;

当我在设置 const FetchedCategories = response.data OR response.data[0].categoryId 后 console.log(response) 时,由于它是一个数组,因此我在终端中收到此错误

WARN 可能未处理的 Promise 拒绝 (id: 4): TypeError: undefined 不是对象(评估“response.data”)

2个回答

您同时使用了 await 和 .then .catch。这将不允许您使用 .catch 捕获错误。您需要使用 try/catch 块来处理错误。例如,您可以按如下方式重写该函数:

...
try {
  const response = await axios(options)

  const fetchedCategories = response.data[0];
  return fetchedCategories;
  // or 
  return response.data[0];

} catch(err) {
  console.log(err)
  // do something with the error
}
...
Arman
2022-12-24

.then 返回未定义, .then((response) => console.log()) ,因此 const response = await axios(options) 返回的响应也是未定义的,更好的方法是使用 try/catch,如其他答案中所建议的

export async function getCategories() {
  const https = "xxxxxx";
  const url = `${https}/api/Category/GetCategories`;

  const userToken ="xxxxxxxx"

  const authStr = "Bearer ".concat(userToken);

  const options = {
    method: "POST",
    headers: {
      Authorization: authStr,
    },
    url: url,
  };

  const response = await axios(options)
    // this returns undefined (response) => console.log()
    //.then((response) => console.log(response.data[0].categoryName))
    .catch((error) => console.log(error.toJSON()));

  const fetchedCategories = response.data[0];
  console.log(
    "🚀 ~ file: menu.js:27 ~ getCategories ~ fetchedCategories",
    fetchedCategories
  );

  return fetchedCategories;
Azzy
2022-12-24