简体   繁体   English

尝试在 React 中实现 Axios

[英]Trying to implement Axios in React

So this is the axios implementation所以这是 axios 实现

import axios from "axios";
axios.interceptors.response.use(null, (error) => {
  console.log("INTERCEPTOR CALLED");
  return Promise.reject(error);
});

And this is the function which is establishing connection.这是正在建立连接的function。 In this first I am updating the state and then requesting server and if something goes south then reverting the state back to original state.首先,我更新 state,然后请求服务器,如果出现问题,则将 state 恢复为原始 state。

handleDelete = async (post) => {
const orginialPosts = this.state.posts;
const posts = this.state.posts.filter((p) => p.id !== post.id);
this.setState({ posts });
try {
  await axios.delete(apiEndpoint + "/" + post.id);
  throw new Error("Pandemic. xd");
} catch (ex) {
  console.log("handle delete catch block");
  if (ex.response && ex.response.status === 404)
    alert("This post has already been deleted");
  alert("Something Failed while deleting a post!");
  this.setState({ posts: orginialPosts });
}
};

So in console it should print:- INTERCEPTOR CALLED handle delete catch block所以在控制台中它应该打印:- INTERCEPTOR CALLED handle delete catch block

Instead it is printing:- handle delete catch block相反,它正在打印: - 处理删除捕获块

I can't figure out why it's happening.我不知道为什么会这样。

And one more thing is there any way to throw error with specific code, something like:-还有一件事是有任何方法可以使用特定代码引发错误,例如:-

throw new Error status(404).

Or creating the whole express handler and then sending response with status code 404 is the only way.或者创建整个快速处理程序,然后发送带有状态码 404 的响应是唯一的方法。

I just wanted to create a Error with status code 404.我只是想用状态码 404 创建一个错误。

The error got resolved, the issue was throw new Error("");错误得到解决,问题是throw new Error(""); was sending a status code of 200 or 204 and the axios interceptor catches error outside the range of 2xx.正在发送 200 或 204 的状态代码,并且 axios 拦截器捕获 2xx 范围之外的错误。 The above code was fine, it was just status code messing up.上面的代码很好,只是状态码搞砸了。

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

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