为什么将 Next.js API 路由与外部 API 一起使用? [英] Why use Next.js API route with an external API?

查看:38
本文介绍了为什么将 Next.js API 路由与外部 API 一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Next.js 的新手.我想知道export default function handler有什么用,因为我们可以使用fetch直接调用API.

I am new in Next.js. I want to know what is the use of export default function handler because we can directly call the API using fetch.

在我的 HTML 代码中,我把代码放在下面.当我点击 submit 按钮时,sendformData() 函数将被调用.

In my HTML code I put below code. When I click on submit button sendformData() function will be called.

<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/文件并调用该函数.

When sendformData function is called, it calls /api/comments/ file and calls the function.

这里是 /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 时,将检索到相同的响应.那么为什么我们需要调用导出默认函数处理程序函数?

When I put the below code in the sendformData same response will be retrieved. So why we need to call export default function handler function?

 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 完全没问题.

If you already have an existing API there's no need to proxy requests to that API through an API Route. It's completely fine to make a direct call to the API.

但是,也有一些想要这样做的用例.来自 API 路由文档:

However, there are some use-cases for wanting to do so. From the API routes documentation:

  • 屏蔽外部服务的 URL(例如 /api/secret 而不是 https://company.com/secret-url)
  • 使用服务器上的环境变量安全地访问外部服务.

本质上,出于安全原因,如果您想要隐藏外部 API URL,或者想要避免向浏览器公开请求所需的环境变量.

Essentially, for security reasons, if you want to hide the external API URL, or want to avoid exposing environment variables needed for a request to the browser.

这篇关于为什么将 Next.js API 路由与外部 API 一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆