首页 > 解决方案 > 如何在 React 中显示来自 django-rest-framework 的错误消息

问题描述

我正在尝试使用 Django 休息框架和反应,redux 来实现用户注册表单。我能够成功注册用户,但是在显示错误时遇到问题,这些错误由 Django 提供,以防出现错误。

到目前为止我做了什么

export const AUTH_START = 'AUTH_START';
export const AUTH_SUCCESS = 'AUTH_SUCCESS';
export const AUTH_FAIL = 'AUTH_FAIL';
export const AUTH_LOGOUT = 'AUTH_LOGOUT';

这是Reducer功能

const initialState = {
    token: null,
    error: null,
    loading: false
}

const authFail = (state, action) => {
    return updateObject(state, {
        error: action.error,
        loading: false
    });

}

const reducer = (state = initialState, action) => {
    switch (action.type) {
        case actionTypes.AUTH_START:
            return authStart(state, action);
        case actionTypes.AUTH_SUCCESS:
            return authSuccess(state, action);
        case actionTypes.AUTH_FAIL:
            return authFail(state, action);
        case actionTypes.AUTH_LOGOUT:
            return authLogout(state, action);
        default:
            return state;
    }
}

export default reducer;

export const updateObject = (oldObject, updatedProperties) => {
    return {
        ...oldObject,
        ...updatedProperties
    }
}

这是商店功能

export const authFail = (error) => {

    return {
        type: actionTypes.AUTH_FAIL,
        error: error
    }

}
export const authSignup = (username, email, password1, password2) => {
    return dispatch => {
        dispatch(authStart());
        axios.post('http://127.0.0.1:8000/rest-auth/registration/', {
            username: username,
            email: email,
            password1: password1,
            password2: password2
        }).then(res => {
            const token = res.data.key;
            const expirationDate = new Date(new Date().getTime() + 3600 * 1000);
            localStorage.setItem('token', token);
            localStorage.setItem('expirationDate', expirationDate);
            dispatch(authSuccess(token));

            dispatch(checkAuthTimeOut(3600));
        }).catch(err => {
            dispatch(authFail(err))

        })
    }
}

这是settings.py

INSTALLED_APPS = [
    'django.contrib.sites',
    'allauth',
    'allauth.account',
    'allauth.socialaccount',
    'corsheaders',
    'rest_auth',
    'rest_auth.registration',
    'rest_framework',
    'rest_framework.authtoken',

]

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.TokenAuthentication',
    )
}

标签: javascriptnode.jsreactjsecmascript-6redux

解决方案


您可以像这样从服务器获得完整的错误响应

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

因此,如果您有错误,您可以使用 dispatch 来分派类似这样的错误

dispatch(displayError(error.message));
dispatch(displayError(error.response.data));
dispatch(displayError(error.response.status));

推荐阅读