JavaScript post请求错误422与FastApi python服务器



我只是想用javascript和python做一个简单的登录页面。网站应该发送一个post请求到我的python api。但是我得到错误422,这意味着不可处理的实体和javascript不打印json响应,所以我不明白为什么我得到422错误。

JavaScript代码:

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);

和我的python服务器代码:

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)

接受任何帮助

我不认为你可以设置这样的路由没有导入flask。我认为无效的数据可能来自于此。下面是一些可以提供帮助的包:

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

操作系统。Path允许您在需要时使用文件

我发现了错误。这只是因为"模式":"no-cors"。参数。当我删除这个参数时,我成功地工作了。最后的代码是这样的:

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);

根据以下文章

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

注意模式:"no-cors"类中只允许有限的一组标头要求:

接受

接收语言

内容语言

Content-Type值为application/x-www-form-urlencoded, multip美术/形式-数据,或文本/纯文本

因此,请求标头"Content-Type"仍然是文本/纯文本,导致422错误。

一个解决方案是删除"模式"属性从获取请求中获取。您可以在本地主机上运行服务器,以防止CORS问题。

最新更新