簡體   English   中英

使用 Nextjs React 前端從 Fastapi 端點檢索數據時出現問題

[英]Problem retrieving data from Fastapi endpoint with Nextjs React frontend

@router.get('/public',response_class=HTMLResponse)
def job_list_view(request:Request):
    async def get_todos() -> dict:
        todos = [
        {
            "id": "1",
            "item": "Read a book."
        },
        {
            "id": "2",
            "item": "Cycle around town."
        }
            ]
        return { "data": todos }

當我嘗試使用 Postman 訪問該端點時,出現“內部服務器錯誤”

當我嘗試使用 Nextjs 應用程序訪問該端點時:

export async function getServerSideProps() {
  const jobs = await fetch('http://localhost:8000/public/')
  console.log(jobs)
  const res = jobs.json()
  return {
    props: { jobs: res },
  }
}

我收到以下錯誤:

    error - unhandledRejection: FetchError: invalid json response body at http://localhost:8000/public/ reason: Unexpected token I in JSON at position 0
    error - Error: Error serializing `.jobs` returned from `getServerSideProps` in "/".
    Reason: `object` ("[object Promise]") cannot be serialized as JSON. Please only return JSON serializable data types.

在我的 Fastapi 后端控制台中,我得到“AttributeError:'dict' object has no attribute 'encode'”,如下所示:

INFO:     127.0.0.1:63133 - "GET /public/ HTTP/1.1" 500 Internal Server Error
ERROR:    Exception in ASGI application
Traceback (most recent call last):
  File "D:\TEMP\job_search - SQL\venv\lib\site-packages\uvicorn\protocols\http\h11_impl.py", line 366, in run_asgi       
    result = await app(self.scope, self.receive, self.send)
  File "D:\TEMP\job_search - SQL\venv\lib\site-packages\uvicorn\middleware\proxy_headers.py", line 75, in __call__       
    return await self.app(scope, receive, send)
  File "D:\TEMP\job_search - SQL\venv\lib\site-packages\fastapi\applications.py", line 269, in __call__
    await super().__call__(scope, receive, send)
  File "D:\TEMP\job_search - SQL\venv\lib\site-packages\starlette\applications.py", line 124, in __call__
    await self.middleware_stack(scope, receive, send)
  File "D:\TEMP\job_search - SQL\venv\lib\site-packages\starlette\middleware\errors.py", line 184, in __call__
    raise exc
  File "D:\TEMP\job_search - SQL\venv\lib\site-packages\starlette\middleware\errors.py", line 162, in __call__
    await self.app(scope, receive, _send)
  File "D:\TEMP\job_search - SQL\venv\lib\site-packages\starlette\middleware\cors.py", line 84, in __call__
    await self.app(scope, receive, send)
  File "D:\TEMP\job_search - SQL\venv\lib\site-packages\starlette\middleware\authentication.py", line 48, in __call__    
    await self.app(scope, receive, send)
  File "D:\TEMP\job_search - SQL\venv\lib\site-packages\starlette\exceptions.py", line 93, in __call__
    raise exc
  File "D:\TEMP\job_search - SQL\venv\lib\site-packages\starlette\exceptions.py", line 82, in __call__
    await self.app(scope, receive, sender)
  File "D:\TEMP\job_search - SQL\venv\lib\site-packages\fastapi\middleware\asyncexitstack.py", line 21, in __call__      
    raise e
  File "D:\TEMP\job_search - SQL\venv\lib\site-packages\fastapi\middleware\asyncexitstack.py", line 18, in __call__      
    await self.app(scope, receive, send)
  File "D:\TEMP\job_search - SQL\venv\lib\site-packages\starlette\routing.py", line 670, in __call__
    await route.handle(scope, receive, send)
  File "D:\TEMP\job_search - SQL\venv\lib\site-packages\starlette\routing.py", line 266, in handle
    await self.app(scope, receive, send)
  File "D:\TEMP\job_search - SQL\venv\lib\site-packages\starlette\routing.py", line 65, in app
    response = await func(request)
  File "D:\TEMP\job_search - SQL\venv\lib\site-packages\fastapi\routing.py", line 251, in app
    response = actual_response_class(response_data, **response_args)
  File "D:\TEMP\job_search - SQL\venv\lib\site-packages\starlette\responses.py", line 49, in __init__
    self.body = self.render(content)
  File "D:\TEMP\job_search - SQL\venv\lib\site-packages\starlette\responses.py", line 57, in render
    return content.encode(self.charset)
AttributeError: 'dict' object has no attribute 'encode'

我已經搜索了數百篇文章和文章,但仍然無法解決這個問題。 這里有一個例子: https ://testdriven.io/blog/fastapi-react/ 但我收到了這些錯誤。

您是說您的端點將返回一個 HTML 響應 - 即一個字符串( str ):

@router.get('/public', response_class=HTMLResponse)
                                      ^^^^^^^^^^^^

.. 但您返回的是一個字典,它不是HTML 響應。 相反,只需刪除response_class ,因為您沒有針對架構或當前結構中的任何其他內容驗證您的響應。

@router.get('/public')
def job_list_view(request: Request):
    todos = [
        {
            "id": "1",
            "item": "Read a book."
        },
        {
            "id": "2",
            "item": "Cycle around town."
        }
    ]
    return {"data": todos}

這將以 JSON 格式返回數據,這是您的 JavaScript 代碼嘗試讀取的內容。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM