簡體   English   中英

ServerError: Invalid JSON 響應正文...在 NextJS 應用程序中提取

[英]ServerError: Invalid JSON response body... in NextJS app with fetch

我有一個在本地運行的 nextJS 應用程序,我還有一個在本地運行的 flask api。 我知道 flask 通過 Postman 返回正確的 json。 獲取請求的結果如下:

{
    "results": [
        [
            {
                "date_posted": "Mon, 17 Jan 2022 00:00:00 GMT",
                "description": "This is a description",
                "id": 1,
                "mainImg": "https://i.ibb.co/pwxkyGw/How-the-Web-Works-1.png",
                "slug": "Test-Post",
                "subtitle": "Test Subtitle",
                "tags": "test tag",
                "title": "Test Post 2"
            }
        ]
    ]
}

所以,既然我知道這是正確的,我就開始研究 javascript:

import React from 'react';

export const getStaticPaths = async () => {
    const res = await fetch('http://localhost:3000/search/all')
    const data = await res.json()

    const paths = data.results[0].map(post => {
        return {
            params: { id: post.id.toString() }
        }
    })

    return {
        paths,
        fallback: false
    }
}

export const getStaticProps = async (context) => {
    const id = context.params.id
    const res = await fetch('http://localhost:5000/search/postID/' + id)
    const data = await res.json()

    return {
        props: {data}
    }
}

export default function Post({data}) {
  return (
  <div>
      {props.data}
  </div>
    )
}

我檢查了所有內容,但由於某種原因,我仍然收到此錯誤:

Server Error
Error: invalid json response body at http://localhost:3000/search/all reason: Unexpected token < in JSON at position 0

This error happened while generating the page. Any console logs will be displayed in the terminal window.
Source
pages\post\[pid].js (5:17) @ async getStaticPaths

  3 | export const getStaticPaths = async () => {
  4 |     const res = await fetch('http://localhost:3000/search/all')
> 5 |     const data = await res.json()
    |                 ^
  6 | 
  7 |     const paths = data.results[0].map(post => {
  8 |         return {
Show collapsed frames

我知道我錯過了一些東西,這就是我在這里的原因。 如果有人看到這個並知道解決方法,請告訴我!

所以...如果您查看兩個提取的代碼。 一個說端口 3000,另一個說 5000……它們都應該是 5000。我不敢相信我花了這么長時間才抓住那個 smdh。

暫無
暫無

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

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