我是Next.js的新手。我想知道export default function handler的用途是什么,因为我们可以直接使用fetch调用API。
在我的HTML代码中,我把代码放在下面。当我单击submit按钮时,将调用sendformData()函数。
<input type="button" value="Submit" onClick={() => this.sendformData()} ></input>sendformData = async () => {
const res = await fetch("/api/comments/getTwitFrmUrl?twitUrl=" + this.state.twitUrl, {
headers: {
"Content-Type": "application/json",
},
method: "GET",
});
const result = await res.json();
this.setState({ data: result.data });
};当调用sendformData函数时,它调用/api/comments/文件并调用该函数。

这是/api/comments/[id].js文件代码。
export default async function handler(req, res) {
if (req.query.id == 'getTwitFrmUrl') {
const resData = await fetch(
"https://dev.. .com/api/getTwitFrmUrl?twitId=" + req.query.twitUrl
).then((response) => response.text()).then(result => JSON.parse(result).data);
res.status(200).json({ data: resData });
}
else if (req.query.id == 'getformdata') {
console.log('getformdata api');
res.status(200).json({ user: 'getuserData' });
}
}当我将以下代码放入sendformData中时,将检索相同的响应。那么,为什么我们需要调用export default function handler函数呢?
sendformData = async () => {
const res = await fetch(
"https://dev.. .com/api/getTwitFrmUrl?twitId=" + req.query.twitUrl
).then((response) => response.text()).then(result => JSON.parse(result).data);
const result = await res.json();
this.setState({ data: result.data });
};发布于 2021-10-12 06:44:08
如果您已经有了一个现有的API,则不需要通过API路由将请求代理到该API。直接打个电话是完全可以的。
然而,有一些用例想要这样做。
安全关切
出于安全考虑,您可能希望使用API路由隐藏外部API URL,或者避免公开来自浏览器的请求所需的环境变量。
/api/secret而不是https://company.com/secret-url)避免CORS限制
您还可能希望通过API路由代理请求,以绕过CORS。通过从服务器发出对外部API的请求,将不会应用CORS限制。
https://stackoverflow.com/questions/69521279
复制相似问题