我想做一个登录表单。我使用的是angularjs的ng-submit。当单击提交按钮时,我希望在服务器中调用post方法而不更改url。
express的post
需要一个url来响应。如果我的登录屏幕的url是http://localhost:2000/login
,当提交被点击,我希望post
被调用相同的url http://localhost:2000/login
。
我不知道如何使用$http
的url
键。
登录html:
<form ng-controller="loginController" ng-submit="loginFunc()">
<input type="text" name="" ng-model="login">
<input type="password" ng-model="password" name="">
<input type="submit" value="login" name="">
控制器:
.controller('loginController', function($scope, $http) {
$scope.login = ""
$scope.password = "";
$scope.loginArray = [];
$scope.loginFunc() {
$scope.loginArray.push($scope.login);
$scope.loginArray.push($scope.password);
$http({
method: 'POST',
url: 'loginClick',
data: $scope.loginArray
})
}
})
server.js:
app.get('/login', function(request, response) { //the file sent when /login is requested
response.sendFile(__dirname + "/staticFolder/view/login.html");
})
app.post('/loginCheck', function(request, response) { //call this when submit button is clicked without change in url
console.log(JSON.stringify(request.body) + "req");
})
尝试将登录详细信息作为对象发送,而不是作为数组发送。这会让你的生活更轻松。
.controller('loginController', function($scope, $http) {
$scope.loginFunc() {
$http({
method: 'POST',
url: '/loginCheck', //not loginClick make sure you have a route to handle this.
data: {
login: $scope.login,
password: $scope.password
}
})
.then(function(response) {
//Success handling
}, function(err) {
//Error handling
});
}
})
你必须在每个和每个路由中响应
编辑1 使用backend as:使用相同的url
/login
,但使用不同的http动词(get
和post
)
app.get('/login', function(request, response) { //the file sent when /login is requested
response.sendFile(__dirname + "/staticFolder/view/login.html");
});
app.post('/login', function(request, response) { //call this when submit button is clicked without change in url
console.log(JSON.stringify(request.body) + "req");
/*
below will be the logic for handling your interest.
*/
someIOCall(function Handler(err,resultJson){
if(err)
return res.status(500).end();
res.status(200).end(resultJson)
})
})
您应该发送POST数据作为一个对象,而不是作为一个数组,如果不是express不知道哪个参数有哪个值。
另外,像'loginClick'这样的字符串不能作为url。
试试这样写:
$scope.loginFunc = function(){
$http({
method:'POST',
url:'/login',
data: {
login: $scope.login,
password: $scope.password
}
})
}
不能100%确定'/login'是否足够作为url,如果不能,试着用port等指定绝对url。
如果你想邮寄到/login,你也必须调整你的快递路线:
app.post('/login', function(request,response) {
console.log(JSON.stringify(request.body)+"req");
})