1

When I use a POST request to send form data from a JS script running on port 5500 using XMLHttpRequest to my backend which is a FastAPI app running on port 8000, I am always met with this error Unprocessable Entity. Here is the server-side:

origins = ["https://localhost:5500"]
app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


@app.post("/test")
def test(username: str = Form(...)):
    print(f"########### Received {username} #############")

And here is the client-side code:

async function sendData() {
    formData = new FormData();
    formData.append('username', 'Kareem');
    const response = await fetch('http://localhost:8000/test', {
        method: 'POST',
        data: formData
    })
}
9
  • What is the error in the response body? Commented Nov 16, 2020 at 23:32
  • should the origin a https or http as it is a localhost? Commented Nov 17, 2020 at 4:26
  • @MahirMahbub I've tried both Commented Nov 17, 2020 at 11:50
  • I tried your code in my server. It is working fine. I think their ia configuration error in backend or problem in frontend. Did you tested the api in swgger or other tools? Commented Nov 17, 2020 at 11:53
  • @Mause Response {type: "cors", url: "localhost:8000/test", redirected: false, status: 422, ok: false, …} body: (...) bodyUsed: false headers: Headers {} ok: false redirected: false status: 422 statusText: "Unprocessable Entity" type: "cors" url: "localhost:8000/test" proto: Response Commented Nov 17, 2020 at 11:54

1 Answer 1

0

Hi I had a same problem . I used URLSearchParams.

This is my code

let urlencoded = new URLSearchParams();
urlencoded.append("username", username);
urlencoded.append("password", password);


try {
    setLoading(true);
    const response =  await fetch("http://127.0.0.1:5000/login", {
        method: 'POST',
        headers: {
             "Content-Type" : "application/x-www-form-urlencoded"
        },
        body: urlencoded,
        redirect: 'follow'

    })

Sign up to request clarification or add additional context in comments.

1 Comment

Could you explain a little bit why? The code snippet is throwing an error so it's hard to understand in context.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.