Flask 和获取 POST 请求

问题描述 投票:0回答:1

我正在尝试发送 POST 请求,但收到 500 错误,这是第二天,我一直在尝试解决它, 请帮忙

烧瓶:

from flask import Flask, render_template, redirect, url_for

app = Flask(__name__)


@app.route('/tasks/today')
def homepage():
    return render_template('index.html', action='Мой день')


@app.route('/')
def redirect_to_homepage():
    return redirect('/tasks/today')

@app.route('/post', methods=['GET', 'POST'])
def get_input_text():
    print('Function worked!')

app.run()

Js:

let user = {
    name: 'John',
    surname: 'Smith'
};
  
let response = fetch('/post', {
    method: 'POST',
    headers: {'Content-Type': 'application/json;charset=utf-8'},
    body: JSON.stringify(user)
});

感谢您的帮助

javascript python-3.x flask post fetch
1个回答
0
投票

试试这个

from flask import Flask, render_template, redirect, jsonify

app = Flask(__name__)


@app.route("/tasks/today")
def homepage():
    return render_template("index.html", action="Мой день")


@app.route("/")
def redirect_to_homepage():
    return redirect("/tasks/today")


@app.route("/post", methods=["GET", "POST"])
def get_input_text():
    return jsonify({"message": "hello world"})


if __name__ == "__main__":
    app.run()

如果您在该原因之后遇到错误

CORS
尝试安装Flask-CORS 并像这样更新你的代码

from flask import Flask, render_template, redirect, jsonify, request
from flask_cors import CORS

app = Flask(__name__)

CORS(app)


@app.route("/tasks/today")
def homepage():
    return render_template("index.html", action="Мой день")


@app.route("/")
def redirect_to_homepage():
    return redirect("/tasks/today")


@app.route("/post", methods=["GET", "POST"])
def get_input_text():
    if request.method == "POST":
        return jsonify({"message": "this is post method"})

    return jsonify({"message": "this is get method"})


if __name__ == "__main__":
    app.run()
© www.soinside.com 2019 - 2024. All rights reserved.