AngularJS和JSON的代码问题

Code issue with AngularJS and JSON

本文关键字:代码 问题 JSON AngularJS      更新时间:2023-09-26

我有一个JSON源,并希望通过post请求从它获得结果。

当我在chrome中测试POSTMAN扩展时,它工作得很好。但是当我用angularJS这样做时,页面继续加载,chrome控制台显示错误。

我的代码在这里:

angular.module('loginApp', []).controller('loginController', function ($scope, $http) {
$scope.userName = '';
$scope.userPass = '';
$scope.output = function () {
    var params = JSON.stringify({
            username: '******',
            password: '******'
        });
    $http({url: "http://xx.xx.xx.xx/api/user/login.json",
        method: 'POST',
        data: params,
        headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        }
    }).then(function (response) {
        return response;
    });
};
});

任何帮助都将是感激的:)

试试这个,post后如果出现错误:

var LoginApp = angular.module('loginApp', []);
LoginApp.controller('loginController', function ($scope, $common) {
    $scope.userName = '';
    $scope.userPass = '';
    $scope.output = function () {
        var params = JSON.stringify({
            username: '******',
            password: '******'
        });
        $common.ajax("http://xx.xx.xx.xx/api/user/login.json", params, "POST").then(function (response) {
            console.log(response);
            return response;
        });
    };
});
LoginApp.factory("$common", function($http, $q) {
    function ajax(url, param, method) {
        var request = $http({
            method: method,
            url: url,
            data:param
        });
        var promise = request.then(
            function(response) {
                return(response.data);
            },
            function(response) {
                console.log("Ocurred error: " + response);
                return($q.reject("Something went wrong"));
            }
        );
        return promise;
    }
    return({
        ajax:ajax
    });
});

试试这个:

$scope.output = function () {
    var params = {
      username: '******',
      password: '******'
    };
    $http.post("http://xx.xx.xx.xx/api/user/login.json", params)
      .then(function (response) {
        return response;
      });
};

您还应该将您的http请求移动到service。这是一个不好的做法,把它放在controller