如何在node.js + ajax中向用户发送自定义错误消息
有人可以帮助我通过ajax从服务器发送到客户端的错误信息? 例如,如果我的服务器端返回一个404错误,我希望它也发送一个自定义的消息:“有问题”
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 } });
提前致谢!
在调用send
或json
之前,您只需调用status方法:
res.status(404).send({ error: "Something is wrong"});