如何使用angularjs通过id发送http PUT请求

l5tcr1uw  于 2022-10-24  发布在  Angular
关注(0)|答案(1)|浏览(241)

我已经用Python语言开发了一个REST风格的API,它使用我的数据库和表名为GROUP。我已经创建了脚本,允许我获得和发布,我想要创建的PUT脚本,将更新一个组。在我的html文档上,当你点击一个组时,它会在表单上填写组的详细信息。在此表单上,您应该进行所需的任何更改,然后脚本将使用group_id向我的服务器发送一个PUT请求,并将更新存储到我的数据库中。
Groups.html

<!DOCTYPE html>
<html lang="en">
<head>
    <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.7.5/angular.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <link rel="stylesheet" href="stylesheet.css" />
    <meta charset="UTF-8">
    <title>Groups</title>
</head>
<body>

<div>
    <ul>
  <li><a class="active" href="index.html">Players</a></li>
  <li><a href="#news">Team</a></li>
  <li><a href="#contact">Manager</a></li>
  <li><a href="#about">Stadiums</a></li>
  <li><a href="">Matches</a></li>
  <li><a href="">Leaderboards</a> </li>
  <li><a href="">Groups</a></li>
    </ul>
</div>

<div class="row" ng-app = "app" ng-controller = "getGroups">
    <div class="column" >
        <h1>View Groups</h1>
    <table>
        <tr>
            <th>Group ID</th>
            <th>Group Name</th>
            <th>Team A</th>
            <th>Team B</th>
            <th>Team C</th>
            <th>Team D</th>
        </tr>
        <tbody ng-repeat = "groups in allGroups">
            <tr ng-repeat = "item in groups">
                <td ng-bind = "item.group_id"></td>
                <td ng-bind = "item.group_name"></td>
                <td ng-bind = "item.team_a"></td>
                <td ng-bind = "item.team_b"></td>
                <td ng-bind = "item.team_c"></td>
                <td ng-bind = "item.team_d"></td>
                <td><button ng-click="">Select Group</button></td>
                <td><button ng-click = "deleteGroup(item.group_id)">Delete Group</button></td>
            </tr>
        </tbody>
    </table>
    <br>
        </div>
<div class="column">
    <h1>Add New Group</h1>
    <form name = "addGroup" ng-submit = "submit()">
        <label>Group Name: </label><input type = "text" name = "Group Name" ng-model = "form.group_name"><br>
        <label>Team A: </label><input type = "text" name = "Team A" ng-model = "form.team_a"><br>
        <label>Team B: </label><input type = "text" name = "Team B" ng-model = "form.team_b"><br>
        <label>Team C: </label><input type = "text" name = "Team C" ng-model = "form.team_c"><br>
        <label>Team D: </label><input type = "text" name = "Team D" ng-model = "form.team_d"><br>
        <input type = "submit" value="Add New Group">
    </form>
    </div>

    <div class="column">
        <h1>Update Group</h1>
        <form class="data-form" name="updateGroup" ng-submit="updateGroups(update.group_id)">
            <label>Group ID</label><input type="text" name="Group ID" ng-model="update.group_id" readonly><br>
            <label>Group Name: </label><input type = "text" name = "Group Name" ng-model = "update.group_name"><br>
            <label>Team A: </label><input type = "text" name = "Team A" ng-model = "update.team_a"><br>
            <label>Team B: </label><input type = "text" name = "Team B" ng-model = "update.team_b"><br>
            <label>Team C: </label><input type = "text" name = "Team C" ng-model = "update.team_c"><br>
            <label>Team D: </label><input type = "text" name = "Team D" ng-model = "update.team_d"><br>
            <input type = "submit" value="Update Group">
        </form>

    </div>
</div>

<script>
    var app = angular.module('app',[]);

    app.controller('getGroups', function($scope, $http)
    {
        $http({
            method: "GET",
            url: "http://127.0.0.1:5000/api/v1/groups"
        }).then(function onSuccess(response) {
            $scope.allGroups = response.data;
        }, function error(response) {
            $scope.allGroups = response.statusText;
            alert("Something went wrong: Error No. 1")
        });

        $scope.submit = function()
        {
            $http({
                method: "POST",
                url: "http://127.0.0.1:5000/api/v1/groups",
                data: $scope.form,
                headers: { 'Content-Type' : 'application/json' }
            }).then(function onSuccess(response) {
                alert("Group has been added");
            }, function error() {
                alert("Something has gone wrong: Error No. 2");
            });
        };

        $scope.updateGroups = function(id)
        {
            $http({
                method: "PUT",
                url: ("http://127.0.0.1:5000/api/v1/groups/" + id),
                data: $scope.form,
            }).then(function onSuccess(response) {
                alert("Group has been added");
            }, function error() {
                alert("Opps")
            });
        };

        $scope.deleteGroup = function(id)
        {
            $http({
                method: "DELETE",
                url: ("http://127.0.0.1:5000/api/v1/groups/" + id),
            }).then(function onSuccess() {
                alert("Group has been deleted");
            }, function error() {
                alert("Something went wrong: Error No. 3");
            });
        };
    });

    $(document).ready(function () {
        $("td", this).on("click", function () {
            var tds = $(this).parents("tr").find("td");
            $.each(tds, function (i, v) {
                $($(".data-form input")[i]).val($(v).text());
            });

        });

    });
</script>

</body>
</html>

这是我的$scope.updateGroups IM遇到的问题,它应该接受表单中的id,并使用它在数据库中存储更新的详细信息

<form class="data-form" name="updateGroup" ng-submit="updateGroups(update.group_id)">
            <label>Group ID</label><input type="text" name="Group ID" ng-model="update.group_id" readonly><br>
            <label>Group Name: </label><input type = "text" name = "Group Name" ng-model = "update.group_name"><br>
            <label>Team A: </label><input type = "text" name = "Team A" ng-model = "update.team_a"><br>
            <label>Team B: </label><input type = "text" name = "Team B" ng-model = "update.team_b"><br>
            <label>Team C: </label><input type = "text" name = "Team C" ng-model = "update.team_c"><br>
            <label>Team D: </label><input type = "text" name = "Team D" ng-model = "update.team_d"><br>
            <input type = "submit" value="Update Group">
        </form>

这就是我正在努力工作的功能:

$scope.updateGroups = function(id)
        {
            $http({
                method: "PUT",
                url: ("http://127.0.0.1:5000/api/v1/groups/" + id),
                data: $scope.form,
            }).then(function onSuccess(response) {
                alert("Group has been added");
            }, function error() {
                alert("Opps")
            });
        };

我觉得我在什么地方犯了个小错误
VM201:1选项127.0.0.1:5000/api/v1/组/未定义的404(未找到)
我在使用CORS时遇到了问题,但我在API-def After_Request(Response)中添加了代码:

response.headers.add('Access-Control-Allow-Origin', '*') 
response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization') 
response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS')
return response

我在控制台中也收到了这个错误
CORS策略已阻止从原始'localhost:63342'访问位于'127.0.0.1:5000/api/v1/groups/undefined'的XMLHttpRequest.CORS策略:对印前检查请求的响应未通过访问控制检查:它没有HTTP ok状态。
但我的GET、POST和DELETE操作正常
我的回复标头是

Access-Control-Allow-Headers: Content-Type,Authorization
Access-Control-Allow-Methods: GET,PUT,POST,DELETE,OPTIONS 
Access-Control-Allow-Origin: *

我认为这应该会让PUT请求通过。但是我收到了一个404错误,URL是127.0.0.1:5000/api/v1/groups/undefined,而undefined应该是通过表单传递的id
我的API.py文件,其中包含我的路线


# Import statements

import mysql.connector
from flask import Flask, abort, jsonify, request

# Global Constants

VERSION = 'v1'
BASE_URI = '/api/' + VERSION
GROUPS = '/groups'
GROUP = '/group'
URI_FOR_ALL_GROUPS = BASE_URI + GROUPS
MYSQL_USER = 'root'
MYSQL_PASS = ''
MYSQL_HOST = 'localhost'
MYSQL_DB = 'football'

# Creating an instance of Flask

app = Flask(__name__)

def create_connection():  # Method to Create Connection to Database
    return mysql.connector.connect(user=MYSQL_USER,
                                   password=MYSQL_PASS,
                                   host=MYSQL_HOST,
                                   database=MYSQL_DB)

# POST: Adding a new Group

@app.route(URI_FOR_ALL_GROUPS, methods=['POST'])
def add_group():
    # Method to add Group
    if not request.json:
        abort(400)
    conn = create_connection()
    cursor = conn.cursor()
    query = "INSERT INTO groups(group_name, team_a," \
            "team_b, team_c, team_d)" \
            "values (%s, %s, %s, %s, %s)"
    cursor.execute(query, (request.json['group_name'],
                           request.json['team_a'],
                           request.json['team_b'],
                           request.json['team_c'],
                           request.json['team_d']))
    id = cursor.lastrowid
    conn.commit()
    query = "SELECT * FROM groups WHERE group_id=" + str(id)
    cursor.execute(query)
    row = cursor.fetchone()
    group = {}
    for (key, value) in zip(cursor.description, row):
        group[key[0]] = value
    conn.close()

    return jsonify(group), 201

# GET: Get a single groups information

@app.route(URI_FOR_ALL_GROUPS + '/<int:id>', methods=['GET'])
def get_group(id):
    # Method to retrieve the information of a single group
    conn = create_connection()
    cursor = conn.cursor()
    query = "SELECT * FROM groups WHERE group_id=" + str(id)
    cursor.execute(query)
    row = cursor.fetchone()
    group = {}
    for (key, value) in zip(cursor.description, row):
        group[key[0]] = value
    conn.close()

    return jsonify(group), 200

# GET Retrieve all the groups

@app.route(URI_FOR_ALL_GROUPS, methods=['GET'])
def get_groups():
    # Method to retrieve all groups
    conn = create_connection()
    cursor = conn.cursor()
    query = "SELECT * FROM groups"
    cursor.execute(query)
    rows = cursor.fetchall()
    groups = []
    for row in rows:
        dict = {}
        for (key, value) in zip(cursor.description, row):
            dict[key[0]] = value
        groups.append(dict)
    conn.close()

    return jsonify({'groups': groups}), 200

# PUT: Updating a group

@app.route(URI_FOR_ALL_GROUPS + '/<int:id>', methods=['PUT'])
def update_group(id):
    # Method to update a group
    conn = create_connection()
    cursor = conn.cursor()
    query = "UPDATE groups SET group_name=%s, team_a=%s," \
            "team_b=%s, team_c=%s, team_d=%s " \
            "WHERE group_id=%s"
    cursor.execute(query, (request.json['group_name'],
                           request.json['team_a'],
                           request.json['team_b'],
                           request.json['team_c'],
                           request.json['team_d'], id))
    conn.commit()
    query = "SELECT * FROM groups WHERE group_id=" + str(id)
    cursor.execute(query)
    row = cursor.fetchone()
    group = {}
    for (key, value) in zip(cursor.description, row):
        group[key[0]] = value
    conn.close()

    return jsonify(group), 200

# DELETE: Deleting a group

@app.route(URI_FOR_ALL_GROUPS + '/<int:id>', methods=['DELETE'])
def delete_group(id):
    # Method to delete a single group
    conn = create_connection()
    cursor = conn.cursor()
    query = ("DELETE FROM groups WHERE group_id = %d" % id)
    cursor.execute(query)
    conn.commit()

    return jsonify('Group Deleted'), 200

@app.after_request
def after_request(response):
  response.headers.add('Access-Control-Allow-Origin', '*')
  response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization')
  response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS')
  return response

if __name__ == '__main__':
    app.run(debug=True)

这是我用来删除组的html和脚本代码

<tbody ng-repeat = "groups in allGroups">
            <tr ng-repeat = "item in groups">
                <td ng-bind = "item.group_id"></td>
                <td ng-bind = "item.group_name"></td>
                <td ng-bind = "item.team_a"></td>
                <td ng-bind = "item.team_b"></td>
                <td ng-bind = "item.team_c"></td>
                <td ng-bind = "item.team_d"></td>
                <td><button ng-click="">Select Group</button></td>
                <td><button ng-click = "deleteGroup(item.group_id)">Delete Group</button></td>

$scope.deleteGroup = function(id)
        {
            $http({
                method: "DELETE",
                url: ("http://127.0.0.1:5000/api/v1/groups/" + id),
            }).then(function onSuccess() {
                alert("Group has been deleted");
            }, function error() {
                alert("Something went wrong: Error No. 3");
            });
        };
zbdgwd5y

zbdgwd5y1#

该问题由服务器端触发。
您的API不允许“未定义”绑定到您的路由参数。尝试创建一个普通的“foo”服务,它只返回200。当你发球的时候,我打赌你的发球会很顺利。
在您可以验证您的服务层支持HTTP PUT请求之后,您可以关注为什么您的客户端没有正确地将参数绑定到所需的调用。
在检查客户端期间,您可能希望在控制器中为update分配其group_id的点设置断点。你没有在你的样品中提供。
现在您已经提供了更多的上下文,客户端问题似乎与您将模型引用从deleteGroup块中的item切换到在updateGroups块中使用update有关。如果你把你的‘更新’引用改为引用item,我相信你会改变你的结果。不过,要让它对您起作用,您必须将更新表单推入中继器,以便中继器可以访问正在更新的适当的组项目。在这一点上,我相信您将正确地对您的服务调用进行参数化。在此更改后,您的视图可能不是您希望的样子,但您必须单独解决这一问题。需要说明的是,这不是我编写Angular 代码的方式,所以我不会把它作为解决问题的明智方法(特别是因为我不知道您试图解决什么问题),但是考虑到您提供的代码,我相信这是您绑定问题的症结所在。

相关问题