首页 > 解决方案 > 在 html 中显示服务器错误

问题描述

我正在验证我必须通过 ajax 发送的表单,我正在使用 axios 来执行此操作,但我现在想知道是否有办法将我从服务器收到的错误显示到我的 html 中,这些是我的错误想展示 在此处输入图像描述

我在服务器端使用 django rest-framework 这是我的代码

axios({
            method: 'post',
            url: `${baseURL}api/users/`,
            contentType: 'application/json',
            data : {} // I send the inputs data here
        })
        .then(response => {
            window.location.href = '/success.html';
            console.log(response)
        })
        .catch(err => {
            console.log(`It works ${err.message}`);
        })

这样做,我只能显示这样的消息

'它工作请求失败,状态码为 400'

标签: djangopython-3.xerror-handlingdjango-rest-framework

解决方案


尝试类似:

var errors = {}
...
.then(response => {
    window.location.href = '/success.html';
    console.log(response)
    errors = Object.assign({})
})
.catch(err => {
    errors = Object.assign({}, err.data['error'])
    console.log(`It works ${err.message}`);
})

然后,您可以使用此变量在 html 中显示错误,例如errors['address']


推荐阅读