![](/img/trans.png)
[英]Why does NextJS's getStaticPaths throws an error when I run next build?
[英]NextJS fetch() throws invalid URL error when running next build but next dev works fine
我正在制作 NextJS React 應用程序並嘗試使用此行從我的服務器獲取數據:
let data = await fetch('/api/getAllAlumniInfoList').then(res => res.json())
當我使用next dev
運行服務器時,一切正常。 但是,當我嘗試使用next build
用於生產的應用程序時,出現此錯誤:
(node:173544) ExperimentalWarning: The Fetch API is an experimental feature. This feature could change at any time
(Use `node --trace-warnings ...` to show where the warning was created)
node:internal/deps/undici/undici:5491
throw new TypeError("Failed to parse URL from " + input, { cause: err });
^
TypeError: Failed to parse URL from /api/getAllAlumniInfoList
at new Request (node:internal/deps/undici/undici:5491:19)
at Agent.fetch2 (node:internal/deps/undici/undici:6288:25)
... 4 lines matching cause stack trace ...
at Wc (/app/goatconnect/goatconnect/node_modules/react-dom/cjs/react-dom-server.browser.production.min.js:68:44)
at Zc (/app/goatconnect/goatconnect/node_modules/react-dom/cjs/react-dom-server.browser.production.min.js:70:253)
at Z (/app/goatconnect/goatconnect/node_modules/react-dom/cjs/react-dom-server.browser.production.min.js:76:89)
at Zc (/app/goatconnect/goatconnect/node_modules/react-dom/cjs/react-dom-server.browser.production.min.js:70:481) {
[cause]: TypeError [ERR_INVALID_URL]: Invalid URL
at new NodeError (node:internal/errors:393:5)
at URL.onParseError (node:internal/url:564:9)
at new URL (node:internal/url:644:5)
at new Request (node:internal/deps/undici/undici:5489:25)
at Agent.fetch2 (node:internal/deps/undici/undici:6288:25)
at Object.fetch (node:internal/deps/undici/undici:7125:20)
at fetch (node:internal/process/pre_execution:214:25)
at onSearch (/app/goatconnect/goatconnect/.next/server/pages/coach/alumniView.js:75:30)
at PlayersView (/app/goatconnect/goatconnect/.next/server/pages/coach/alumniView.js:103:9)
at Wc (/app/goatconnect/goatconnect/node_modules/react-dom/cjs/react-dom-server.browser.production.min.js:68:44) {
input: '/api/getAllAlumniInfoList',
code: 'ERR_INVALID_URL'
}
}
關於這個錯誤的另一個奇怪的事情是,我有不同的頁面,它們的結構完全相同,使用相同的邏輯,工作正常,編譯器不會抱怨。 我不確定是什么原因導致這條 API 路線無法被正確識別。
我嘗試使用 NextJS 提供的鈎子useSWR
,它在很多其他情況下都有效,但這個特定用例用於數據庫搜索,因此當使用 API 調用的結果更新頁面時,使用鈎子會導致無限循環。
useSWR 是一個不錯的選擇,但對於 fetch,我建議使用 unfecth 作為 useSWR 的 fetcher。 對我來說沒有問題。
import fetch from 'unfetch'
import useSWR from 'swr'
function YourComponent() {
const { data, error } = useSWR('/api/getAllAlumniInfoList', fetch)
if (error) return <div>failed to load</div>
if (!data) return <div>loading...</div>
return <div>hello {data.name}!</div>
}
使用搜索輸入、useSWR 和無無限循環的更新:
import { ChangeEvent, useCallback, useState } from "react";
import styles from "../styles/Home.module.css";
import fetch from "unfetch";
import useSWR from "swr";
import { debounce } from "lodash";
const fetcher = (url: string) => fetch(url).then((res) => res.json());
export default function Home() {
const [value, setValue] = useState<string>("");
const { data = [], error } = useSWR(
value ? `/api/user/${value}` : null,
fetcher,
{
fallbackData: [],
}
);
const onChange = debounce(
useCallback(
(e: ChangeEvent<HTMLInputElement>) => setValue(e.target.value),
[value]
),
500
);
if (error) {
return <div>An error occured</div>;
}
return (
<div className={styles.container}>
<input onChange={onChange} />
{data?.map((e: any) => (
<div key={Math.random()}>{e.name}</div>
))}
</div>
);
}
重要提示:值不能傳遞給輸入。 只需傳遞 onChange 方法即可。
在 API 一側,帶有虛假數據,文件路徑/pages/api/user/[name].ts
:
import type { NextApiRequest, NextApiResponse } from "next";
type Data = {
name: string;
};
const data: Array<Data> = [
{ name: "John Doe" },
{ name: "Miss Pierce Bogisich" },
{ name: "Beaulah Tillman" },
{ name: "Aracely Hessel" },
{ name: "Margret Berge" },
{ name: "Hailee Macejkovic" },
{ name: "Lazaro Feeney" },
{ name: "Gennaro Rutherford" },
{ name: "Ian Hackett" },
{ name: "Sonny Larson" },
{ name: "Dr. Liza Wolf" },
];
export default function handler(
req: NextApiRequest,
res: NextApiResponse<Array<Data>>
) {
const {
query: { name },
} = req;
console.log(name);
res
.status(200)
.json(
data.filter((e) =>
e.name.toLowerCase().includes(`${name?.toString().toLowerCase()}`)
)
);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.