skip to Main Content

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


  1. Chosen as BEST ANSWER

    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:

    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}),
    
    })
    .then(response => response.text())
    .then(response => console.log(JSON.stringify(response)))
    }
    
    submitBtn.addEventListener("click", submitForm);
    

  2. 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:

    from flask import Blueprint, render_template, redirect, url_for, request, flash
    from flask_login import login_required, current_user
    from os import path
    

    os.path allows you to use files if you need it

    Login or Signup to reply.
  3. According to the following article

    https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#supplying_request_options

    Note that mode: "no-cors" only allows a limited set of headers in the
    request:

    Accept

    Accept-Language

    Content-Language

    Content-Type with a value of application/x-www-form-urlencoded, multip
    art/form-data, or text/plain

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search