Backend
from fastapi import FastAPI, File, Form, UploadFile, Request
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
origins = ["http://127.0.0.1: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} #############")
Frontend
async function sendData() {
formData = new FormData();
formData.append('username', 'Kareem');
const response = await fetch('http://127.0.0.1:8000/test', {
method: 'POST',
data: formData
})
console.log(response)
Response
Response {
body: (...)
bodyUsed: false
headers: Headers {}
ok: false
redirected: false
status: 422
statusText: "Unprocessable Entity"
type: "cors"
url: "http://127.0.0.1:8000/test"
__proto__: Response }
Description
- The
/test endpoint is simply supposed to recieve a form containing only username and print it out.
- When I test the API using swagger docs it works fine as expected, but when I try to send form data from an external script it throws me this error and that response object above.
Environment
- OS: Linux
- FastAPI version: 0.61.1
- Python version: 3.8.2
Click on the three little dots next to body?
Has anyone figured out what the issue was? I have a frontend which must use .fetch() so cannot use XMLHttpRequest.