我在Next.js api路由中使用Listen Notes播客api。我希望来自前端表单的用户查询与Next.js api交互。因此,当用户输入";历史";,它会将其发送到api,以查找有关该主题的播客。我试着向axios请求添加params,但似乎不起作用。
前端:
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);
});
}
如果我需要提供更多信息,请告诉我。
检查NextJs应用程序上的API是否正确接收环境变量process.env.RREACT_app_API_KEY。使用console.log进行测试。
参考:https://nextjs.org/docs/basic-features/environment-variables
另一个检查是API路径,因为NextJ使用您自己的方法来路径,你知道吗?!
参考:https://nextjs.org/docs/api-routes/introduction
希望这些提示对您有所帮助;(
问题出在api路由上,应该是:
.search({ q: req.query.q })
req.params是服务器端的其他东西,这就是为什么它没有通过。