如何在reactjs上发出“失败”通知

时间:2017-08-08 03:12:25

标签: javascript c# ajax reactjs fetch

我的反应是连接到C#asp.net的api,当外键连接到数据库中的其他表时它不会删除数据但是如果其他表上没有连接密钥,它可以删除数据,我希望你明白我的意思......所以这就是我的ajax发送数据要在api上删除的问题 使用此代码

export const deleter = (url, params) => {
    return(dispatch, getState, api) => {
        api += 'api/';
        return fetch(`${api}${url}`, {
            method: 'DELETE',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(params)
        })

        .then(response => response.json())
        .then(result => dispatch(departmentResult(result, types.DELETER)))
        .then(function(response) {
             NotificationManager.success('The department is deleted', 'Department Deleted ')   
         },
         function (error) {
            NotificationManager.error('Sorry but this has already been used', 'ERROR! ')   
         })
         .catch(function(error) {
             NotificationManager.error('Sorry but this has already been used', 'ERROR! ')   
         // any error from "doing stuff" will show up here
         console.error(error);
    });
    }
}

然而它总是显示成功通知,即使它没有被删除,我也不知道为什么,我试图在未删除时输出错误通知。但是此代码的错误部分无法正常工作。希望您能够帮助我。谢谢

2 个答案:

答案 0 :(得分:0)

这是获取API的预期行为。来自docs:

  

当网络错误发生时,fetch()promise将拒绝TypeError   遇到过,虽然这通常意味着许可问题或类似问题    - 例如,404不构成网络错误。

这意味着,如果您的asp.net web api返回常见的HTTP错误状态(如500或400),则不会将其视为错误。要抓住这些,你可以这样做:

dbms_output.put_line(rpad(v_rec1.HIRE_DATE, 15)

答案 1 :(得分:0)

事实证明我的代码构造错误

export const deleter = (url, params) => {
    return(dispatch, getState, api) => {
        api += 'api/';
        return fetch(`${api}${url}`, {
            method: 'DELETE',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(params)
        })      
        .then(function(response) {
         if (response.status <= 200){
             NotificationManager.success('The department is deleted', 'Department Deleted ')
         } else if (response.status <= 500) {
             NotificationManager.error('Sorry but this has already been used', 'ERROR! ')
         } else {
             NotificationManager.error('Sorry, something went wrong', 'ERROR! ')
         }
     },
     function (error) {
        NotificationManager.error('Sorry but this has already been used', 'ERROR! ')
     })
        .then(response => response.json())
        .then(result => dispatch(departmentResult(result, types.DELETER)));

    }
}