我的应用程序中的授权存在一些问题。我通过工厂和控制器,post方法发送请求实现它,但是作为响应我从服务器登录,那些值是错误的。 但是如果我将doLogin函数的主体更改为jQuery ajax方法并且不使用工厂,一切都可以。我的Angular方式出了什么问题?
我的AngularJS代码
形式:
<form ng-submit="doLogin(credentials)">
<div class="list">
<label class="item item-input">
<span class="input-label">Username</span>
<input type="text" ng-model="credentials.email">
</label>
<label class="item item-input">
<span class="input-label">Password</span>
<input type="password" ng-model="credentials.password">
</label>
<label class="item">
<button class="button button-block button-positive" type="submit">Log in</button>
</label>
</div>
</form>
厂:
.factory('Somepost', function ($http) {
return{
doPost: function (credentials, callback) {
console.log('service');
console.log(credentials);
return $http({
url:'http://cronicls.ru/auth/login',
method: 'POST',
data: credentials,
async : true
}).success(callback);
}}})
控制器中的登录功能:
$scope.doLogin = function(credentials) {
var successCallback = function (data) {
console.log(data);
}
Somepost.doPost(credentials, function(data) {
console.log(data);
});
};
函数doLogin with $ .ajax(工作成功):
$scope.doLogin = function(credentials) {
var successCallback = function (data) {
console.log(data);
}
var login = function(credentials, successCallback) {
$.ajax({
type: "POST",
url: 'http://cronicls.ru/auth/login',
async : true,
data: credentials,
success: function(data){
console.log('login success');
console.log(data);
successCallback();
},
error: function(data){
console.log('/auth/login: error');
console.log(data);
}
});
};
login(credentials, successCallback);
};
答案 0 :(得分:1)
但作为回应我已经从服务器登录,那些值是错误的。
其实没有,因为它会返回一个承诺,你必须在回调中做这样的事情:
根据你的评论:
在服务器端使用ZF 的PHP。实际上,您需要将默认内容类型标题从application/json
更改为application/x-www-form-urlencoded
工厂变更:
.factory('Somepost', function ($http) {
return{
doPost: function (credentials, callback) {
console.log('service');
console.log(credentials);
return $http({
url:'http://cronicls.ru/auth/login',
method: 'POST',
data: credentials,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}, // <-- override the default contentType header
async : true
}).then(callback); // change to then instead of success
}}})
答案 1 :(得分:0)
我找到了问题的答案。感谢@Jai对ZF的暗示。实际上我们需要在$ .param()中包装数据。因此,工厂是:
.factory('Somepost', function ($http) {
return{
doPost: function (credentials, callback) {
return $http({
url:'http://cronicls.ru/auth/login',
method: 'POST',
data: $.param(credentials),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(callback);
}
}
})