0

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: enter image description here

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.

miriad
  • 136
  • 3
  • 8

2 Answers2

1

user is whatever string the user typed in.

const user = document.getElementById("email").value;

And you are putting that string into the body, completely raw, and claiming that it is JSON.

    headers: "content-type": "application/json",
    body: user,

It seems unlikely that the user is typing JSON into the email field.

If you tell the server you are sending JSON, then you need to actually send JSON.

While I'm not remotely familiar with FastAPI, it looks like the JSON text that is expected is:

{ "email": "some value" }

So you need to construct that:

body: JSON.stringify({ email: user })
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
-1

Try this on your server.

Your code doesn't have CORS enabled. You need to enable it, if you are using a cross domain request.

from fastapi import FastAPI
from pydantic import BaseModel

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
    }
  • thanks for the suggestion. I've tried this but I'm still not getting a response from the server – miriad Jun 08 '22 at 10:16