如何在 React 中显示来自 django-rest-framework 的错误消息

Posted

技术标签:

【中文标题】如何在 React 中显示来自 django-rest-framework 的错误消息【英文标题】:How to display error messages from django-rest-framework in React 【发布时间】:2019-12-29 10:24:11 【问题描述】:

我正在尝试使用 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',
    )

【问题讨论】:

【参考方案1】:

您可以像这样从服务器完全错误响应

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

【讨论】:

以上是关于如何在 React 中显示来自 django-rest-framework 的错误消息的主要内容,如果未能解决你的问题,请参考以下文章

一直在使用 React,如何设置超时或创建一个类似于每隔几分钟显示来自 graphql api 的新数据的数据轮播?

如何在挂钩中比较来自 react redux 状态的值

目前无法在 React 应用程序中显示来自 API 的 svg 图像

在 React JS 中显示来自 Json 的键值对

使用 Node 服务器在 React App 中显示来自网络驱动器的动态 PDF

如何使用 react.js 上传 Excel 工作表文件并将数据显示到表格中