问题描述
我在将 JSON 从前端发送到后端并在那里读取时遇到了一些问题。
首先是简单的部分,在我的 index.html
中,我阅读了某些字段中的内容并将其传递给 var inputs
<script type="text/javascript">
function get_inputs()
{
var inputs =
{
T_0 : document.getElementById("a").value,E_A : document.getElementById("b").value,}
backend_test(inputs)
console.log("input:" + JSON.stringify(inputs))
return inputs
}
</script>
"console.log("input:" + JSON.stringify(inputs))" 输出到控制台:
输入:{"T_0":"3","E_A":"5"}
这会调用函数 backend_test ,该函数应该接受我所做的输入并通过 GET 请求将其作为 JSON 发送到我的 FastAPI:
function backend_test(inputs)
{
var inputs = inputs
console.log('frontend_func inputs out: ' + JSON.stringify(inputs))
$(document).ready(function() //supposed to wait for the functions to be fully loaded
{
$.ajax({
type: 'GET',contentType: 'application/json',data: JSON.stringify(inputs),dataType: "json",url:"fastapi/compute",success: function (result)
{
console.log(result)
console.log("should work")
},error: function (error)
{
console.log(error)
console.log("error,but where?")
}
});
});
return("yay")
}
现在,在我的后端,我想以某种方式使用这些信息进行进一步的计算:
from fastapi import Request,FastAPI
from pydantic import BaseModel
from .self_ignition import test_function
from typing import List
class Liste(BaseModel):
T_0: int
E_A: int
@app.get("/compute")
def calculate(liste: Liste):
return {"backend output:" + liste}
发送请求,因为它在我的前端控制台中提供了“错误 422 无法处理的实体”,我收到“错误,但在哪里?”在我的“backend_test”函数中定义的消息。 到后端的连接在那里,调用 /compute 并且在 calculate() 中没有任何输入会给我函数 backend_test(inputs) 定义的成功输出:“应该工作”。 我无法直接查看后端代码中的错误,因为一切都在公司的 GitLab 框架中进行设置,并且只有通过提交更改并启动更新的网页才能进行测试。
使用“基本模型”是我在文档中阅读它后的最后一次尝试,从事类似项目但使用不同 API 的人只需要编写“def calculate (body)”,并且有他的信息,但是这在这个 API 中似乎不起作用
请注意,这些只是使连接正常工作的代码的一部分。我真正需要的是了解 FastAPI 如何处理 JSON 的接收,因为文档并没有真正帮助我使其工作。
提前致谢,我在这个小问题上坐了 2 天,不断返回相同的帮助页面,但无法使其正常工作。
解决方案:
将 Number() 添加到这部分,因为我后来将它们称为 int 而不是 str:
T_0 : Number(document.getElementById("a").value),E_A : Number(document.getElementById("b").value),
在此处将类型更改为 POST:
$.ajax({
type: 'POST',
这里:
@app.post("/compute")
并且不要尝试返回列表,而是返回一个将该列表的元素作为 str 的变量:
x=str(liste.T_0)
return {"backend output:"+x}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)