我正在制作一个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
,它在许多其他实例中都能工作,但是这个特定的用例是用于数据库搜索的,所以当页面被更新时,使用钩子会导致无限循环。
发布于 2022-11-21 18:29:38
useSWR是一个很好的选择,但是对于fetch,我建议使用unfecth作为useSWR的获取器。对我来说没有问题。
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端,带有假数据的filepath /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()}`)
)
);
}
https://stackoverflow.com/questions/74523191
复制相似问题