React 未显示来自 FastAPI 后端应用程序的 POST 响应

React not showing POST response from FastAPI backend application

我有一个简单的 React Ui,它应该从 localhost:8000/todo 获取 json 文件并在 localhost:3000 中创建 Ui。 这是所需的输出:

然而,这是我得到的:

所以,这两行是“读一本书”。和“在城里骑自行车”。没有显示。这两行应该来自localhost:8000/todo,这是一个JSON类型的信息。我觉得我可以从 localhost:8000/todo 获取数据,但我不知道如何在 localhost:3000 中显示它们,这是我的输出。

这是我的功能:

export default function Todos() {
  const [todos, setTodos] = useState([])
  const fetchTodos = async () => {
    const response = await fetch("http://localhost:8000/todo")
    const todos = await response.json()
    setTodos(todos.data)
  }
  useEffect(() => {
    fetchTodos()
  }, [])
  return (
    <TodosContext.Provider value={{todos, fetchTodos}}>
      <AddTodo />  
      <Stack spacing={5}>
        {todos.map((todo) => (
          <b>{todo.item}</b>
        ))}
      </Stack>
    </TodosContext.Provider>
  )
}

{todos.item} 是应该打印项目的部分,但它没有!

这是控制台日志信息:

这是来自 localhost:8000/todo 的回复:

如果您需要更多信息,请告诉我。

您需要启用 CORS (Cross-Origin Resource Sharing) in the backend. You can configure it in your FastAPI application using the CORSMiddleware

注:

Origin

An origin is the combination of protocol (http, https), domain (myapp.com, localhost, localhost.tiangolo.com), and port (80, 443, 8080).

So, all these are different origins:

  • http://localhost
  • https://localhost
  • http://localhost:8080

Even if they are all in localhost, they use different protocols or ports, so, they are different "origins".

示例如下:

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()

origins = ["http://localhost:3000"]

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)