[英]Why does this curl command work but not my post request via python?
[英]Why does my python server save the post request data to the database as “0”?
我正在开发一个全栈应用程序(react/flask)。 我正在尝试通过来自客户端的 POST 请求发送表单数据,但数据在数据库中保存为“0”。 反应代码工作正常,但发送的数据保存为“0”。 你们能帮我吗?
这是 flask 代码:
from flask import Flask, jsonify, request
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import Column, String
import os
from flask_marshmallow import Marshmallow
app = Flask(__name__)
basedir = os.path.abspath(os.path.dirname(__file__))
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'hi.db')
app.config['JWT_SECRET_KEY'] = 'super-secret' # change this IRL
db = SQLAlchemy(app)
ma = Marshmallow(app)
@app.route('/', methods=['GET','POST'])
def welcome():
email = request.form.get('email', False)
test = List.query.filter_by(email=email).first()
if test and request.method =="POST":
return jsonify(message='This email already exists. Please enter a different email.'), 409
else:
name = request.form.get('name', False)
user = List(name=name, email=email)
db.session.add(user)
db.session.commit()
return jsonify(message="Thank you for Joining my app waiting list. we promise we won't spam your email!"), 201
# database models
class List(db.Model):
id = Column(db.Integer, primary_key=True)
email = Column(String(120), unique=True, nullable=False)
name = Column(String(50), nullable=False)
if __name__ == '__main__':
app.run()
这是反应代码:
import React, { useState } from "react";
import { Form, Button } from 'react-bootstrap'
export default function Users() {
const [email, setEmail] = useState("");
const [name, setName] = useState("");
return (
<div>
<Form>
<Form.Group controlId="formBasicEmail">
<Form.Label>Email address</Form.Label>
<Form.Control
type="email"
// name= "email"
placeholder="Enter email"
value={email}
onChange={e => setEmail(e.target.value)} />
<Form.Text className="text-muted">
We'll never share your email with anyone else.
</Form.Text>
</Form.Group>
<Form.Group controlId="formBasicPassword">
<Form.Label>Name</Form.Label>
<Form.Control
type="text"
// name="name"
placeholder="Enter Your Name"
value={name}
onChange={e => setName(e.target.value)}
/>
</Form.Group>
</Form>
<Button
variant="primary"
type="submit"
onClick={async () => {
const credential = { email, name };
const response = await fetch("/", {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded"
},
body: credential
});
if (response.ok) {
console.log("response worked!");
console.log("body", credential)
}
}}>
Submit
</Button>
</div>
)
}
您的请求正文类型为 JSON 但您的 Content-Type header 设置为“application/x-www-form-urlencoded”,因此您的请求正文应为 FormData: Z5E056C500A1C4Borg6A7110/BADEmo0d8文档/Web/API/FormData
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.