首页 > 解决方案 > 为什么我收到的是 post 请求而不是 get 请求?

问题描述

我使用烧瓶作为我的后端。每次我从“/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)```

标签: pythonreactjsflask

解决方案


我怀疑问题出在您的 HTML/javascript/react 代码上。您的问题中没有所有 html,但我认为它看起来像这样:

<form method=POST>
<button onclick="console.log('posting your api')" type=submit>Press Me</button>
</form>

您可能在表单中有一个按钮。当您单击按钮时,onclick js 会按预期发布。

鉴于您设置了要提交的类型,您的按钮可能连接到一个表单。该表单可能配置为发布到我猜测的当前页面/home


推荐阅读