gpt4 book ai didi

angularjs - 如何在 express/node js 中发送错误 http 响应?

转载 作者:IT老高 更新时间:2023-10-28 23:00:52 27 4
gpt4 key购买 nike

所以在登录页面中,我通过获取请求从 Angular 发送凭据以表达。我想做的是,如果在数据库中找到,发送响应并以 Angular 处理它,否则如果在数据库中找不到我想表达发送错误响应并处理它的 Angular 错误响应函数,但我的代码不起作用。

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.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");
}
});
}

最佳答案

在带有 ExpressJS 的 Node 中,您可以使用 res.status() 发送错误:

return res.status(400).send({
message: 'This is an error!'
});

在 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
}
);

关于angularjs - 如何在 express/node js 中发送错误 http 响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35864088/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com