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

标签 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

最佳答案

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

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

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

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

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

关于javascript - AngularJS 问题(不允许 POST 405 方法),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39391053/

相关文章:

c# - 从 VAT eu 解析一个 json

json - 在 Swift 中读取 JSON 文件

php - 如何使用 PHP 通过 JSON 发送 HTML 元素?

javascript - '未捕获的语法错误 : Unexpected token u' when using JSON. 解析

Javascript 使用异步加载本地 .txt 文件

javascript - JqueryUI 拖动 : Cursor not at the same position as draggable element

javascript - karma 和 phantomJS 有什么区别

javascript - HTML5 视频 canPlay 事件第二次不起作用

javascript - Angular 2 - 找不到模块 ' ng-factory'

json - 如何在来自 json 文件的 angularjs Controller 警报中显示翻译文本?