AngularJS问题(POST 405方法不允许)

时间:2016-09-08 12:33:50

标签: javascript angularjs json http

我是Angular的新手。我正在学习$ http服务,目前正试图通过POST发送JSON数据。不幸的是,我收到了一个错误。我试着阅读其他人关于这个问题的帖子,但我似乎无法理解这个问题是什么。

任何人都可以帮助我理解为什么我会收到此错误并建议修复方法吗?

HTML

<!DOCTYPE html>
<html ng-app = "app">
<head>
    <title></title>
</head>
<body ng-controller = "ctrl">
    <form>
        <input type="text" ng-model = "newDJ_name">
        <button ng-click = "addDJ(newDJ_name)">Add new DJ name</button>
        <button ng-click = "show()">Show DJs</button>
    </form>

    <div ng-repeat = "dj in djs">

        {{dj.name}}

    </div>
</body>

<script src = "angular.min.js"></script>
<script src = "httpService.js"></script>

</html>

的Javascript

var app = angular.module ("app",[]);

app.controller ("ctrl",function ($scope,$http) {
$scope.show = function () {
        $http.get('djs.json').success(function(data){
            $scope.djs = data;
        })
    };
$scope.addDJ = function (newName) {
        $http.post('http://localhost:8080/Documents/Angular/djs.json',{name : newName})
        .success(function(data) {
            $scope.djs = data;
        })
        .error (function(data) {
            console.log(":(");
        })
    }


});

JSON文件

[{
    "name": "Adam Beyer",
    "city": "Sweden",
    "genre": "techno",
    "label": "Drumcode"
}, {
    "name": "Richie Hawtin",
    "city": "Detroit",
    "genre": "techno",
    "label": "Minus"
}, {
    "name": "Solomun",
    "city": "Undefined",
    "genre": "techno",
    "label": "Dyinamic"
}]

When I try to add a new dj name

1 个答案:

答案 0 :(得分:1)

您正尝试将数据直接发送到.json文件。这是不可能的。

相反,在服务器上编写一个webservice端点: - 接受“POST”短语和有效负载数据 - 将数据写入文件(在您的情况下为.JSON文件) - 根据创建文件的成功或失败,向Angular应用程序返回有意义的响应。

注意 - 如果您尝试更新已包含数据的.JSON文件,则可能需要将现有文件解析为JSON,使用新数据进行变更,然后将其保存回文件。

如果您要将网络服务短语更改为GET,通常应该看到成功的响应:

// This will work
$http.get('http://localhost:8080/Documents/Angular/djs.json')