May*_*iya 23 javascript reactjs next.js
我是 Next.js 的新手。我想知道 的用途是什么,export default function handler因为我们可以使用 直接调用API fetch。
在我的 HTML 代码中,我放置了以下代码。当我单击submit按钮时sendformData(),将调用函数。
<input type="button" value="Submit" onClick={() => this.sendformData()} ></input>
Run Code Online (Sandbox Code Playgroud)
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 });
};
Run Code Online (Sandbox Code Playgroud)
当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' });
}
}
Run Code Online (Sandbox Code Playgroud)
当我将下面的代码放入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 });
};
Run Code Online (Sandbox Code Playgroud)
jul*_*ves 43
如果您已有 API,则无需通过API 路由代理对该 API 的请求。直接调用它是完全可以的。
\n然而,有一些用例需要这样做。
\n出于安全原因,您可能希望使用 API 路由来隐藏外部 API URL,或避免暴露浏览器请求所需的环境变量。
\n\n\n\n
\n- 屏蔽外部服务的 URL(例如
\n/api/secret代替https://company.com/secret-url)- 使用服务器上的环境变量安全地访问外部服务。
\n\xe2\x80\x94 Next.js、API 路由、用例
\n
您可能还想通过 API 路由代理请求以规避 CORS。通过从服务器向外部 API 发出请求,将不会应用 CORS 限制。
\n