[英]How to pass user query to Next.js api?
I'm using the Listen Notes podcast-api in Next.js api routes.我在 Next.js api 路由中使用 Listen Notes podcast-api 。 I want the user query from my front-end form to interact with the Next.js api.
我希望我的前端表单中的用户查询与 Next.js api 交互。 So when a user inputs "history", it will send that to the api to look for podcasts that are about that topic.
因此,当用户输入“历史”时,它会将其发送到 api 以查找有关该主题的播客。 I tried adding params to axios request but that doesn't seem to work.
我尝试将参数添加到 axios 请求中,但这似乎不起作用。
Front-end:前端:
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 code: 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);
});
}
Please let me know if I need to provide more information.如果我需要提供更多信息,请告诉我。
Check if API on you NextJs app, is receiving correctly the environment variable process.env.REACT_APP_API_KEY .检查 NextJs 应用程序上的 API 是否正确接收环境变量process.env.REACT_APP_API_KEY 。 Use console.log to test.
使用console.log进行测试。
Reference: https://nextjs.org/docs/basic-features/environment-variables参考: https://nextjs.org/docs/basic-features/environment-variables
Another check is the API path, cause NextJs use your own method to path this, you know?!另一个检查是 API 路径,因为 NextJs 使用你自己的方法来路径这个,你知道吗?!
Reference: https://nextjs.org/docs/api-routes/introduction参考: https://nextjs.org/docs/api-routes/introduction
Hope this tips help you;)希望这些提示对您有所帮助;)
The problem was in the api route, it should be:问题出在 api 路由中,应该是:
.search({ q: req.query.q })
req.params is something else on server side and that's why it wasn't coming through. req.params 是服务器端的其他东西,这就是它没有通过的原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.