gpt4 book ai didi

javascript - 为什么将 Next.js API 路由与外部 API 一起使用?

转载 作者:行者123 更新时间:2023-12-04 17:10:38 25 4
gpt4 key购买 nike

我是 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/文件并调用函数。
enter image description here
这里是 /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 });
};

最佳答案

如果您已有 API,则无需通过 API 路由代理对该 API 的请求。直接调用 API 完全没问题。
但是,有一些想要这样做的用例。来自 API routes documentation :

  • Masking the URL of an external service (e.g. /api/secret instead of https://company.com/secret-url)
  • Using Environment Variables on the server to securely access external services.

本质上,出于安全原因,如果您想要隐藏外部 API URL,或者想要避免向浏览器公开请求所需的环境变量。
您可能还希望通过 API 路由的代理请求来规避 CORS 限制。通过从服务器向外部 API 发出请求,将不会应用 CORS。

关于javascript - 为什么将 Next.js API 路由与外部 API 一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69521279/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com