I am working on a full-stack app( react/flask). I am trying to send form data via POST request from the client, but the data is being saved as "0" in the database. the react code works fine but the sent data is saved as "0". Can you guys please help me with that?
Here is the flask code:
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()
Here is the react code:
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>
)
}
Your request body is of type JSON but your Content-Type header is set to "application/x-www-form-urlencoded", so your request body should be FormData: https://developer.mozilla.org/en-US/docs/Web/API/FormData
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.