首页 > 解决方案 > 如何在我的 Restful API 中使用 Angular JS

问题描述

我使用flask和python开发了一个restful api。我创建了一个 html 页面,该页面将显示我的组表并允许我添加和删除组。我想使用 Angularjs 从我的 restful api 中获取数据并将其显示在我的 html 页面上,并允许我从我的组表中添加、更新、删除和查看我的组。下面是我的 Restful API

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

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

这是我创建的 html 页面

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

<div ng-app = "app" ng-controller = "getGroups">
    <table>
        <tr>
            <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_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 = "deleteGroup(item.group_id)">Delete Group</button></td>
            </tr>
        </tbody>
    </table>
    <br>

    <form name = "addGroup" ng-submit = "submit()">
        <label>Group Name: </label><input type = "text" name = "Group Name" ng-model = "form.group_name" required ng-pattern = "[a-zA-z]*"><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">
    </form>
</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.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");
            });
        };
    });
</script>

</body>
</html>

当我运行我的网页时,我的警报显示为错误 1,并且我的组未显示在我的表上。我不确定我是否遗漏了什么。我的 restful api 工作正常,我可以查看 api/v1/groups 上的表格内容。


对不起,我的错,这是我在浏览器控制台上遇到的错误

错误:[$parse:ueoe] https://errors.angularjs.org/1.7.5/$parse/ueoe?p0=%5Ba-zA-z%5D* at angular.js:99 at p.consume (angular .js:16101) 在初级 (angular.js:15976) 在 p.unary (angular.js:15960) 在 p.multiplicative (angular.js:15950) 在 p.additive (angular.js:15938) 在 p.在 p.logicalAND (angular.js:15912) 在 p.logicalOR (angular.js:15904) ""

CORS 策略已阻止从源“localhost:63342”访问“127.0.0.1:5000/api/v1/groups”处的 XMLHttpRequest:请求的资源上不存在“Access-Control-Allow-Origin”标头。

标签: pythonangularjsrestapicors

解决方案


显然这是一个 CORS 问题。请在您的响应标头中返回相关标头 Access-Control-Allow-Origin 以及发送请求的域名或 *(不推荐)以允许所有域。


推荐阅读