如何在我的Restful API中使用Angular JS

时间:2018-12-03 00:15:28

标签: python angularjs rest api cors

我已经使用flask和python开发了一个宁静的api。我创建了一个html页面,该页面将显示我的网上论坛表格,并允许我添加和删除网上论坛。我想使用Angularjs从我宁静的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,并且我的组未显示在表上。我不确定是否遗漏了一些东西。我宁静的api可以正常工作,并且可以在api / v1 / groups上查看表内容。


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

  

错误:[$ parse:ueoe] https://errors.angularjs.org/1.7.5/$parse/ueoe?p0=%5Ba-zA-z%5D*在p.unary(angular.js:15976)在p.consume(angular.js:16101)在p.consume(angular.js:16101) :15960)在p.multiplicative(angular.js:15950)在p.additive(angular.js:15938)在p.relational(angular.js:15929)在p.equality(angular.js:15920)在p。 p.logicalOR(angular.js:15904)处的logicalAND(angular.js:15912)“”

  

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

1 个答案:

答案 0 :(得分:1)

很明显,这是一个CORS问题。请在响应标头中返回相关标头Access-Control-Allow-Origin,标头中包含发送请求的域名或*(不建议使用)以允许所有域。