In the Axios document:
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);
});
we know we can catch the error
in the .catch()
method.
But when I use the Django-Rest-Framework as the backend API provider. it only provide the data, there is no status in it:
You see the error
:
{username: ["A user with that username already exists."]}
but in the browser, we can know the status code:
Before asking this question, I have read How can I get the status code from an http error in Axios? this post.
But the post seems different with mine.
EDIT-1
In my Django-Rest-Framework project:
the view:
class UserCreateAPIView(CreateAPIView):
serializer_class = UserCreateSerializer
permission_classes = [AllowAny]
queryset = User.objects.all()
the serializer:
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
I find in the interceptors
configuration:
Axios.interceptors.response.use(
res => {
return res;
},
error => {
return Promise.reject(error.response.data)
}
);
I was return the error.response.data
directly, I could configure it to error.response
, or error
.
if I configure the error.response
, then in the .catch()
I can console like bellow:
console.log(response.data);
console.log(response.status);
console.log(response.headers);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With