【发布时间】: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