【问题标题】:How to send custom error message to user in node.js + ajax如何在 node.js + ajax 中向用户发送自定义错误消息
【发布时间】:2016-05-24 20:12:13
【问题描述】:

有人可以帮助我通过 ajax 从服务器向客户端发送错误消息吗?例如,如果我的服务器端返回 404 错误,我希望它也发送自定义消息:'something is wrong'

server.js

api.get('/api/some_route', function(req, res, next) {

    res.sendStatus(404, 'something is wrong');

});

client.js

$.ajax({
    type: "POST",
    data: data,
    success: function(data, status) {
        console.log(status);
    },
    error: function(jqXHR, textStatus, errorThrown) {
        console.log(textStatus) //returns error
        console.log(errorThrown) //returns bad request
        //I want to someohow print the 'something is wrong' message from the api
    }
});

提前致谢!

【问题讨论】:

    标签: javascript ajax node.js error-handling


    【解决方案1】:

    你只需要在调用sendjson之前调用status方法:

    res.status(404).send({ error: "Something is wrong"});
    

    【讨论】:

    • 我试过这个。仍然是ajax成功。我怎样才能把它扔进ajax错误?
    猜你喜欢
    • 2015-04-17
    • 1970-01-01
    • 1970-01-01
    • 2020-11-07
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    • 2019-01-26
    相关资源
    最近更新 更多