【发布时间】: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