Javascript code:
const submitHandler = async (e) => {
const user = document.getElementById("email").value;
await fetch('https://clownfish-app-fqu4k.ondigitalocean.app/meadow', {
method: "POST",
headers: "content-type": "application/json",
body: user,
})
}
Python:
from fastapi import FastAPI
from pydantic import BaseModel
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
class User(BaseModel):
email: str
@app.post("/meadow")
def password_validation(user: User):
return {
"status": "success",
"data": user
}
The above works fine in Postman, but in Chrome gives the following error:
Any help would be appreciated.
I've updated the code to include the suggestions below. No joy. The request results in a 422 error - an "Unprocessable Entity". Should I be using the FormData class as mentioned in this answer? I've also tried setting the fetch headers to 'accept'.
UPDATE My request is resulting in a
{"detail":[{"loc":["body"],"msg":"value is not a valid dict","type":"type_error.dict"}]}
so I'm not sending the data in the way Pydantic is expecting it
UPDATE 2 Novice mistake - I wasn't stringifying the data before sending it. See @Quentin's answer below.