【问题标题】:Internal Next.js API call returns 500 Error内部 Next.js API 调用返回 500 错误
【发布时间】:2023-01-26 02:38:21
【问题描述】:

对于我的生活,我无法弄清楚为什么我正在进行的内部 API 调用 (Next.js) 不断返回可怕的 500 错误。此处的目标是调用内部 API (Next.js),然后调用后端的 Flask 服务器以检索一些数据(文档)。

据我所知,pages/documentation.js 中的调用不会在api/documentation.js 中执行任何请求。我在 Flask 服务器中设置了日志记录来注释发出的任何请求。

在前端,我看到了Unhandled Runtime Error - SyntaxError: The string did not match the expected pattern.。在检查控制台时,我看到 500 Internal Server Error - http://localhost:3000/api/documentation && Unhandled Promise Rejection: SyntaxError: The string did not match the expected pattern.

我现在被困住了。不知道我还能用谷歌搜索什么来更深入地研究这个问题。我缺乏网络开发经验在这里困扰着我。任何帮助是极大的赞赏。

/* pages/documentation.js */

 // State Variables
 const [documentation, setDocumentation] = useState(null);

  useEffect(() => {
    if (!documentation) {
      fetchDocumentation();
    }
  }, []);  

  // API Call to fetch documentation
  async function fetchDocumentation() {
    const fetchResponse = await fetch('/api/documentation', {
      method: 'get',
      headers: {
        'Content-type': 'application/json',
        'Accept': 'application/json'
      }
    });
    if (!fetchResponse.ok) {
      setDocumentation(await fetchResponse.text());
    } else {
      setDocumentation(await fetchResponse.json());
    }
  };
/* api/documentation.js */

import fetch from 'isomorphic-unfetch'
import getConfig from 'next/config'

const { publicRuntimeConfig } = getConfig();
const BACKEND_API_URL = publicRuntimeConfig.BACKEND_API_URL;

export default async function documentationHandler(req, res) {  
  if (req.method === 'GET') {
    let reqURL = BACKEND_API_URL + '/api/documentation';

    const backendResponse = await fetch(reqURL, {
      mode: 'cors',
      method: 'get',
      headers: {
        'Content-type': 'application/json',
        'Accept': 'application/json'
      }
    });
    if (!backendResponse.ok) {
      return res.status(backendResponse.status).send(await backendResponse.text());
    } else {
      const resp = await backendResponse.json();
      res.status(200).send(resp);
    }
  } else {
    res.status(403).send('Forbidden');
  }
}

【问题讨论】:

  • 您的后端服务的日志对错误有何说明?
  • 500,如果您的错误编码正确,则表明服务器存在问题。您的后端是否正常运行?你能用邮递员或浏览器点击它吗?
  • 在我用来启动前端的 VSCode 终端内,我看到 error - TypeError: fetch failed。至于后端,在前端尝试发出请求时不会创建任何日志语句。我已经通过使用 Postman 发出我在 sn-p 中显示的 GET 请求来手动验证 Flask 服务器是否正常工作。
  • 您应该在前端代码中进行类似的检查。不要盲目相信 fetch() 请求成功
  • 我无法从前端的 fetch() 请求中提取更多信息。

标签: javascript node.js next.js fetch-api http-status-code-500


【解决方案1】:

好吧,因为你正在使用 fetch() 并且你想使用 get 方法,所以可能不需要指定方法作为 get 你可以直接执行此操作 里面

const FetchResponse = await fetch('/api/documentation')
const documentation = await FetchResponse.json()
if(documentation) setDocumentation(documentation)

对于 /api/documentation.js 好好检查你的代码我真的不知道你为什么这样做

let reqURL = BACKEND_API_URL + '/api/documentation';

const backendResponse = await fetch(reqURL, {
  mode: 'cors',
  method: 'get',
  headers: {
    'Content-type': 'application/json',
    'Accept': 'application/json'
  }
});
if (!backendResponse.ok) {
  return res.status(backendResponse.status).send(await backendResponse.text());
} else {
  const resp = await backendResponse.json();
  res.status(200).send(resp);
}

我猜你是想发回对 api 调用的响应……如果是这样,那不是正确的方法…… 下面可以做

const do_something = async (res) =>{
  // fetch documentation from db using sequelize or direct sql
  //when done you can send back the results via api response
if(results) return res.status(200).send(results); // you back the results like this
return res.status(500).send("Ooops! something went wrong");
}
  export default async function documentationHandler(req, res) {  
  if (req.method === 'GET') return await do_something()//get data from db
  res.status(403).send('Forbidden');
  }

【讨论】:

  • 我仔细检查了所有 http 请求方法,并将其全部大写。但是,我仍然在启动应用程序的 VSCode 终端中看到 error - TypeError: fetch failed
  • 我已经编辑了解决方案....抱歉回复晚了
猜你喜欢
  • 2020-05-10
  • 2013-02-26
  • 1970-01-01
  • 2020-06-03
  • 2018-11-09
  • 1970-01-01
  • 1970-01-01
  • 2020-10-13
  • 2017-08-16
相关资源
最近更新 更多