为什么Flask request.form可与<form> POST请求一起使用,而不能与fetch()调用一起使用

时间:2018-10-12 17:50:38

标签: json post flask fetch uwsgi

作为参考,我正在测试在本地计算机上与uWSGI服务器一起运行的flask应用程序。

当我使用这样的表单元素执行POST请求时:

<form action="http://127.0.0.1:5000/" method="post">
    <input type="text" name="username" />
    <input type="text" name="password" />
    <input type="submit" value="Submit">
</form>

烧瓶应用程序的request.form正常运行:

from flask import Flask
from flask import jsonify
from flask import request
app = Flask(__name__)

@app.route('/', methods=['post'])
def get_json():
    username = request.form['username'] # Stores username
    password = request.form['password'] # Stores password

但是,当我使用javascript进行提取调用时,却收到了(400错误的错误请求),

window.onload = function() {
    var data = {
            name: "SomePerson",
            password: "#$%#$%#$"
      }
    fetch("http://127.0.0.1:5000/", {
      method: "post",
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },

      body: JSON.stringify(data)
    })
    .then( (response) => {
        console.log(response)
    });
}

并且烧瓶应用程序的request.form是一个空的ImmutableDict:

from flask import Flask
from flask import jsonify
from flask import request
app = Flask(__name__)

@app.route('/', methods=['post'])
def get_json():
    username = request.form['username'] # Crashes here
    password = request.form['password'] 

0 个答案:

没有答案