I just want to make a simple login page with javascript and python. Website should send a post request to my python api. But I am getting error 422 which means Unprocessable entity and javascript doesnt print the json response so I cant understand why I am getting 422 error.
My JavaScript code:
const submitBtn = document.getElementById("submit");
function submitForm(event) {
event.preventDefault();
const nameInput = document.getElementById("fname").value;
const passwdInput = document.getElementById("passwd").value;
console.log({"first_name": nameInput, "password": passwdInput})
const url = "http://192.168.1.5:800/login";
fetch('http://192.168.1.5:800/login', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({first_name:nameInput, password: passwdInput}),
mode: 'no-cors',
})
.then(response => response.text())
.then(text => {
const json = JSON.parse(text);
console.log(json);
})
.catch(error => console.error(error));
}
submitBtn.addEventListener("click", submitForm);
And my python server code:
from fastapi import FastAPI , Response, status, HTTPException
import uvicorn
import socket
from pydantic import BaseModel
from fastapi.params import Body
import sqlite3
from fastapi.middleware.cors import CORSMiddleware
import json
class login(BaseModel):
first_name: str
password: str
app = FastAPI()
origins = ["*"]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.post("/login")
def login(data: login):
print(data.first_name, data.password)
return {"message": "Got It!"}
if __name__ == "__main__":
uvicorn.run(app, host=IPAddr, port=800)
Any help is accepted.
3
Answers
I found the error. It was just because the "mode: 'no-cors'" parameter. When I remove this parameter I worked succesfully. So final code is something like this:
I don’t think you can set up routes like that without importing flask. I think the invalid data may be from that. Here are some packages to help:
os.path allows you to use files if you need it
According to the following article
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#supplying_request_options
Due to this, the request header "Content-Type" remains text/plain causing the 422 error.
One solution would be to remove the "mode" attribute from the fetch request. You could run the server on localhost to prevent CORS issues.