reactjs NextJS fetch()在运行下一个构建时抛出无效URL错误,但下一个开发工作正常

a8jjtwal  于 2022-11-22  发布在  React
关注(0)|答案(1)|浏览(192)

我正在创建一个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调用的结果更新页面时导致无限循环。

bqujaahr

bqujaahr1#

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>
}

使用搜索输入、使用SWR和无无限循环进行更新:

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()}`)
      )
    );
}

相关问题