【问题标题】:How to pass user query to Next.js api?如何将用户查询传递给 Next.js api?
【发布时间】:2022-01-09 05:41:59
【问题描述】:

我在 Next.js api 路由中使用 Listen Notes podcast-api。我希望我的前端表单中的用户查询与 Next.js api 交互。因此,当用户输入“历史”时,它会将其发送到 api 以查找有关该主题的播客。 我尝试将参数添加到 axios 请求,但这似乎不起作用。

前端:

export default function SearchBar() {
  const [query, setQuery] = useState("");
  const [address, setAddress] = useState("");
  const fetcher = async (url) => await axios.get(url, { params: {q: query } }).then((res) => res.data);
  const { data, error } = useSWR(address, fetcher);

  const handleSubmit = (e) => {
    setAddress(`/api/podcast`);
    e.preventDefault();
  };

  return (
    <>
      <Form onSubmit={handleSubmit}>
        <Input
          onChange={(e) => setQuery(e.target.value)}
        />
        <SearchButton type="submit">Search</SearchButton>
      </Form>
    </>
  );
}

API 代码:

const { Client } = require("podcast-api");

export default function handler(req, res) {
  const client = Client({
    apiKey: process.env.REACT_APP_API_KEY || null,
  });

  //"q" below should contain the user query from front-end
  client     
    .search({ q: req.params })
    .then((response) => {
      res.status(200).json(response.data);
    })
    .catch((error) => {
      console.log("apiError: " + error);
    });
}

如果我需要提供更多信息,请告诉我。

【问题讨论】:

    标签: javascript node.js axios next.js


    【解决方案1】:

    检查 NextJs 应用上的 API 是否正确接收环境变量 process.env.REACT_APP_API_KEY。使用 console.log 进行测试。

    参考: https://nextjs.org/docs/basic-features/environment-variables

    另一个检查是API路径,因为NextJs使用你自己的方法来路径,你知道吗?!

    参考: https://nextjs.org/docs/api-routes/introduction

    希望这些提示对您有所帮助;)

    【讨论】:

    • API 密钥在控制台中正确显示。这也显示在控制台中:“API 已解析但未发送 /api/podcast?q=test 响应,这可能会导致请求停止。”这意味着它可以识别我认为的 req.params?
    • 调用方法对吗?尝试使用“res.status(200).json(response.data);”上的 try/catch 调试 API 上的任何错误,并在控制台记录此内容。
    【解决方案2】:

    问题出在api路由上,应该是:

    .search({ q: req.query.q })
    

    req.params 是服务器端的其他东西,这就是它没有通过的原因。

    【讨论】:

      猜你喜欢
      • 2019-04-15
      • 2021-03-14
      • 1970-01-01
      • 2019-01-04
      • 1970-01-01
      • 2020-06-26
      • 2017-06-25
      • 2017-03-08
      • 2022-12-02
      相关资源
      最近更新 更多