axios如何在.catch()中获取状态码?

8
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() 方法中捕获错误。

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

enter image description here

你看到了这个错误:error
{username: ["A user with that username already exists."]}  

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

enter image description here


在提出这个问题之前,我已经阅读了如何从Axios的http错误中获取状态码?这篇文章。但是这篇文章似乎与我的不同。

编辑-1

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

视图:

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
1个回答

4
我在拦截器配置中发现以下内容:

interceptors

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接