gpt4 book ai didi

javascript - $resource service .success 不是函数

转载 作者:可可西里 更新时间:2023-11-01 09:58:57 24 4
gpt4 key购买 nike

我想用AngularJS、Node和MongoDB实现登录方法。我在发送请求时构建了一个 Restful API。

当我尝试执行 GET 请求时,此错误出现在控制台 TypeError: UserService.logIn(...).success is not a function

成功不像 $http 方式那样存在?

我也找到了这个,但我不明白如何调整它以适合我的代码。

  • HTTP GET“类” Action :Resource.action([参数], [成功],[错误])

  • 非 GET“类”操作:Resource.action([parameters], postData,[成功], [错误])

  • 非 GET 实例操作:instance.$action([parameters], [success],[错误])

Service.js

var appServices = angular.module('starter.services', ['ngResource']);

appServices.factory('UserService', function ($resource) {
return {
logIn: function (email, password) {
return $resource("http://localhost:3000/users/login", {
email: email,
password: password
});
}
}
});

Controller.js

    var apps = angular.module('starter.controller', []);
apps.controller('loginCtrl', function ($scope, $ionicPopup, $state, UserService) {

$scope.doLogin = function doLogin(email, password) {


if (email != null && password != null) {

UserService.logIn(email, password).success(function (data) {
$state.go('tabs.home');

}).error(function (status, data) {

var ionicPop = $ionicPopup.alert({
title: 'Login Failed',
template: 'Invalid email or password.\nPlease try again!'
});
console.log(status);
console.log(data);
});
}
};
});

最佳答案

您的 UserService.logIn() 方法未按预期运行的原因是,您正在返回一个新的 Resource 实例,但从未真正调用它的方法。

// This returns an instance of Resource, which is configured incorrectly.
// The second argument suggests that the URL has :email and :password
// parameters, which it does not. As a result, the email and password
// would be appended to the URL as query params (very insecure!).
return $resource("http://localhost:3000/users/login", {
email: email,
password: password
});

有了$resource,你可以定义额外的方法或者修改现有的getsavequerydelete 方法。但是,这仅对支持 CRUD operations 的 API 端点有用。 .

对于登录调用,您不需要创建资源,因为您不会执行 CRUD 操作。请改用 $http

var appServices = angular.module('starter.services', ['ngResource']);

appServices.factory('authService', function ($http) {
return {
logIn: function (email, password) {
return $http({
url: 'http://localhost:3000/users/login',
method: 'POST',
data: {
email: email,
password: password
},
headers: {
'Content-Type': 'application/json'
},
withCredentials: true
});
}
}
});

以上示例假设您要在请求正文中传递用户凭据。假设您使用的是 SSL,这没问题,但首选方法是使用 Authorization header 。例如,Basic Auth会更安全一些。

更新

事实证明,$resource 的方法不会返回 Promise。它们返回一个资源实例,带有一个 $promise 属性。因此,例如,您可以执行以下操作:

// Using the .save() method, which performs a POST
$resource('http://localhost:3000/users/login').save({email: 'foo@bar.com', password: 'baz'})
.$promise.then(handleSuccess, handleError);

不过,我建议使用 $http 作为登录端点。但是,如果您需要使用 $resource,请查看 this plunker .

关于javascript - $resource service .success 不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34256322/

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