$http.post undefined 不是函数

$http.post undefined is not a function

本文关键字:函数 undefined http post      更新时间:2023-09-26

我正在尝试在这个控制器中实现一个简单的带有角度的$http帖子。

app.controller('LoginCtrl',['$scope','admin','$http',function($scope,$http,admin){
    $scope.isAdmin = admin.isAdmin;
    $scope.logout = admin.logout;
    $scope.login = function(){
        if(!$scope.username || !$scope.password ){ return; }
        $http.post('/login',{ username: $scope.username, password: $scope.password });
        $scope.username = '';
        $scope.password = '';
    };
}]);

这部分

$http.post('/login',{ username: $scope.username, password: $scope.password });

正在抛出此错误

TypeError: undefined is not a function
    at l.$scope.login (http://localhost:3000/javascripts/angularApp.js:165:9)
    at hb.functionCall (http://ajax.googleapis.com/ajax/libs/angularjs/1.3.10/angular.min.js:198:426)
    at Cc.(anonymous function).compile.d.on.f (http://ajax.googleapis.com/ajax/libs/angularjs/1.3.10/angular.min.js:214:485)
    at l.$get.l.$eval (http://ajax.googleapis.com/ajax/libs/angularjs/1.3.10/angular.min.js:126:193)
    at l.$get.l.$apply (http://ajax.googleapis.com/ajax/libs/angularjs/1.3.10/angular.min.js:126:419)
    at HTMLFormElement.<anonymous> (http://ajax.googleapis.com/ajax/libs/angularjs/1.3.10/angular.min.js:215:36)
    at HTMLFormElement.c (http://ajax.googleapis.com/ajax/libs/angularjs/1.3.10/angular.min.js:32:363)

这是 UI 视图的 HTML。

<script type="text/ng-template" id="/login.html">
    <button id="logout" class="btn btn-default" ng-click="logout()" ng-show="isAdmin()">Log Out</button>
    <div ng-controller="LoginCtrl">
      <form id="login" ng-submit="login()">
        <h2>The Login Page.</h2>
        <label>Username:</label>
        <input type="text" ng-model="username" placeholder="username"/>
        <label>Password:</label>
        <input type="password" ng-model="password" placeholder="password"/>
        <button type="submit" class="btn btn-primary">Submit</button>
      </form>
    </div>
  </script>

我已经检查了语法,一切看起来都正确,$http控制台时被识别为对象.log它在控制器范围内。然而,由于某种原因,我无法发出此帖子请求,因为抛出了错误。我正在使用 expressjs 来提供内容,而我目前的"/login"路由只是一个简单的 response.send('response 已发送!')。正如您在 HTML 中看到的那样,我正在使用角度 ui-router,其中我也为它设置了一个 .state,如果需要提供,请告诉我。

对此感到沮丧,因为这是众所周知的功能,我无法在网上找到任何资源来帮助我解决确切的问题。我尝试在标题和其他在线解决方案中设置内容类型,但没有任何帮助。看起来这可能是一些愚蠢的东西,但我找不到它。

我将不胜感激任何意见或帮助,谢谢。

依赖注入顺序错误

app.controller('LoginCtrl', ['$scope', 'admin', '$http',function($scope, $http, admin) { ...

应该是

app.controller('LoginCtrl', ['$scope', '$http', 'admin', function($scope, $http, admin) { ...