javascript - axios如何获取.catch()中的状态码?

标签 javascript python django django-rest-framework axios

Axios文档:

axios.get('/user/12345')
  .catch(function (error) {
    if (error.response) {
      // The request was made and the server responded with a status code
      // that falls out of the range of 2xx
      console.log(error.response.data);
      console.log(error.response.status);
      console.log(error.response.headers);
    } else if (error.request) {
      // The request was made but no response was received
      // `error.request` is an instance of XMLHttpRequest in the browser and an instance of
      // http.ClientRequest in node.js
      console.log(error.request);
    } else {
      // Something happened in setting up the request that triggered an Error
      console.log('Error', error.message);
    }
    console.log(error.config);
  });

我们知道我们可以在 .catch() 方法中捕获 error

但是当我使用 Django-Rest-Framework 作为后端 API 提供者时。它只提供数据,里面没有状态:

enter image description here

您看到了错误:

{username: ["A user with that username already exists."]}  

但是在浏览器中,我们可以知道状态码:

enter image description here


在问这个问题之前,我已经阅读了How can I get the status code from an http error in Axios? 这篇文章。

但是帖子好像和我的不一样。


EDIT-1

在我的 Django-Rest-Framework 项目中:

View :

class UserCreateAPIView(CreateAPIView):
    serializer_class = UserCreateSerializer
    permission_classes = [AllowAny]
    queryset = User.objects.all()

序列化器:

class UserCreateSerializer(ModelSerializer):
    """
    user register
    """
    class Meta:
        model = User
        fields = [
            'username',
            'wechat_num',
            'password',
        ]
        extra_kwargs = {
            "password":{"write_only":True}
        }

    def create(self, validated_data):
        username=validated_data.pop('username')
        wechat_num = validated_data.pop('wechat_num')
        password=validated_data.pop('password')

        user_obj = User(
            username=username,
            wechat_num=wechat_num,
        )
        user_obj.set_password(password)
        user_obj.save()
        group=getOrCreateGroupByName(USER_GROUP_CHOICES.User)
        user_obj.groups.add(group)

        return validated_data

最佳答案

我在拦截器配置中找到:

Axios.interceptors.response.use(
  res => {

    return res;
  },
  error => {

    return Promise.reject(error.response.data)
  }
);

我是直接返回error.response.data,我可以将它配置为error.response,或者error

如果我配置了 error.response,那么在 .catch() 中我可以像下面这样控制台:

console.log(response.data);
console.log(response.status);
console.log(response.headers);

关于javascript - axios如何获取.catch()中的状态码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49273858/

相关文章:

python - 在python中为列表创建第二行并将列表写入txt文件

python - Django 自引用模型过滤器ForeignKey

django - 创建 View 并将值分配给两个 OneToOneFields

javascript - 为什么 Closure Compiler 会破坏这个 AngularJS 脚本?

javascript:变量名之间花括号的含义

javascript - 将 Grocery Grocery 文本编辑器选项从高级更改为简单

python - Pandas 面板 : Copy versus view

python - matplotlib.scatter() 不能在 Python 3.6 上使用 Numpy

django - Django 模板中的新行

javascript - 实现 jQuery 动画表单