为什么我收到的是 post 请求而不是 get 请求?

时间:2021-05-13 04:38:42

标签: python reactjs flask

我使用 Flask 作为我的后端。每次我从“/api-quotes”请求一个post方法时,它也会从“/home”请求一个post方法,即使它只有一个get方法。我不断收到错误消息,“请求的 URL 不允许使用该方法。”在浏览器上。有什么办法可以解决这个问题吗?

<Button onClick={() => {axios.post('/api-quotes', {text: predictMessage})}} type="submit">Generate</Button>

这是我的 React 表单。

from flask import Blueprint, render_template, Flask, jsonify, request, g
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
from flask_cors import CORS
from flask_session import Session
from datetime import datetime
from sqlalchemy import Column, ForeignKey, Integer, String, desc
import os
import logging 
import random

basedir = os.path.dirname(os.path.abspath(__file__))

app = Flask("__name__")
CORS(app)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'posts2.db')
app.config['SQLALCHEMY_BINDS'] = {'quotes': 'sqlite:///' + os.path.join(basedir, 'quotes.db')}
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
ma = Marshmallow(app)

class Posts(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    displayName = db.Column(db.String)
    image = db.Column(db.String)
    text = db.Column(db.String)
    username = db.Column(db.String)#, nullable=False)
    verified = db.Column(db.Boolean)
    avatar = db.Column(db.String)
    date_created = db.Column(db.DateTime, default=datetime.utcnow)

    def __init__(self, id, displayName, image, text, username, verified, avatar):
        self.id = id
        self.displayName = displayName
        self.image = image
        self.text = text
        self.username = username
        self.verified = verified
        self.avatar = avatar

class PostsSchema(ma.Schema):
    class Meta:
        fields = ('id', 'displayName', 'image', 'text', 'username', 'verified', 'avatar', 'date_created')

post_schema = PostsSchema()
posts_schema = PostsSchema(many=True)

@app.route("/api", methods = ['GET', 'POST'])
def api():
    if request.method == 'POST':
        id = Posts.query.order_by('id').all()[-1].id + 1
        displayName = request.json['displayName'] 
        print(request.get_json())
        image = request.json['image'] 
        text = request.json['text'] 
        username = request.json['username'] 
        verified = request.json['verified']
        avatar = request.json['avatar']
        new_posts = Posts(id, displayName, image, text, username, verified, avatar)
        db.session.add(new_posts)
        db.session.commit()
        print(db)
        return post_schema.jsonify(new_posts)
    if request.method == 'GET':
        all_posts = Posts.query.order_by(desc(Posts.id))
        result = posts_schema.dump(all_posts)
        return jsonify(result)

class Quotes(db.Model):
    __bind_key__ = 'quotes'
    id = db.Column(db.Integer, primary_key=True)
    category = db.Column(db.String)
    text = db.Column(db.String)
    date_created = db.Column(db.DateTime, default=datetime.utcnow)

    def __init__(self, id, category, text):
        self.id = id
        self.category = category
        self.text = text

class QuotesSchema(ma.Schema):
    class Meta:
        fields = ('id', 'category', 'text')

quote_schema = QuotesSchema()
quotes_schema = QuotesSchema(many=True)

@app.route("/api-quotes", methods = ['GET', 'POST'])
def apiquotes():
    items = ['Good days will come.', 'Keep calm and carry on!',
    'Treat others the way you want to be treated', 'Life is meaningless without happiness',
    'They may have talent, but you have determination']
    if request.method == 'POST':
        print("Post request to quotes")
        id = Quotes.query.order_by('id').all()[-1].id + 1
        category = 'quotes' 
        text = items[random.randrange(len(items))]
        new_quotes = Quotes(id, category, text)
        print("Inserting to new_quotes")
        db.session.add(new_quotes)
        print("Added new quotes")
        db.session.commit()
        print("Returning quotes")
        print(new_quotes)
        print(quote_schema.jsonify(new_quotes))
        return quote_schema.jsonify(new_quotes)
    if request.method == 'GET':
        print("Sending get to quotes")
        all_quotes = Quotes.query.order_by(desc(Quotes.id))
        result = quotes_schema.dump(all_quotes)
        return jsonify(result)

@app.route("/home", methods = ['GET'])
def my_index():
    print("Getting /home")
    return render_template('index.html')

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

0 个答案:

没有答案