如何在 express/node js 中发送错误 http 响应?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35864088/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to send error http response in express/node js?
提问by Mohammed Gadiwala
So in login page I am sending credentials from angular to express through get request.What I wanna do is that if found in database,send response and handle it in angular else if not found in db I want express to send error response and handle it angular error response function but my code isnt working.
因此,在登录页面中,我从 angular 发送凭据以通过 get 请求表达。我想要做的是,如果在数据库中找到,则发送响应并以 angular 处理它,如果在 db 中找不到,我想表达发送错误响应并处理它角度错误响应功能,但我的代码不起作用。
Angular controller:
角度控制器:
myapp.controller('therapist_login_controller', ['$scope', '$localStorage', '$http',
function($scope, $localStorage, $http) {
$scope.login = function() {
console.log($scope.username + $scope.password);
var data = {
userid: $scope.username,
password: $scope.password
};
console.log(data);
$http.post('/api/therapist-login', data)
.then(
function(response) {
// success callback
console.log("posted successfully");
$scope.message = "Login succesful";
},
function(response) {
// failure callback,handle error here
$scope.message = "Invalid username or password"
console.log("error");
}
);
}
}
]);
APP.js:
APP.js:
app.post('/api/therapist-login', therapist_controller.login);
Controller:
控制器:
module.exports.login = function(req, res) {
var userid = req.body.userid;
var password = req.body.password;
console.log(userid + password);
Credentials.findOne({
'userid': [userid],
'password': [password]
}, function(err, user) {
if (!user) {
console.log("logged err");
res.status(404); //Send error response here
enter code here
} else {
console.log("login in");
}
});
}
回答by michelem
In Node with ExpressJS you can use res.status()to send the error:
在带有 ExpressJS 的 Node 中,您可以使用res.status()来发送错误:
return res.status(400).send({
message: 'This is an error!'
});
In Angular you can catch it in the promise response:
在 Angular 中,您可以在 promise 响应中捕获它:
$http.post('/api/therapist-login', data)
.then(
function(response) {
// success callback
console.log("posted successfully");
$scope.message = "Login succesful";
},
function(response) {
// failure callback,handle error here
// response.data.message will be "This is an error!"
console.log(response.data.message);
$scope.message = response.data.message
}
);
回答by Vlad
Or use instance of Errorclass
或者使用Error类的实例
response.status(code).send(new Error('description'));

