【问题标题】:How to fetch data from an external api (Heroku) with Next JS?如何使用 Next JS 从外部 api (Heroku) 获取数据?
【发布时间】:2021-07-29 11:41:01
【问题描述】:

我目前正在开发一个 Web 应用程序,它的服务器和 Web 应用程序是分开部署的。我已经在 Heroku 上部署了我的服务器和数据库,而我使用 Vercel 来部署我的 Next JS 应用程序。

我的问题是当我使用 isomorphic-unfetch 从 Vercel 发出请求时,它会在请求中添加我的应用程序的地址 (https://myapp.vercel.app/myapp.herokuapp.com/)。我只希望 http://myapp.herokuapp.com 成为请求。

这就是我为它编写代码的方式。

import fetch from 'isomorphic-unfetch'
const host = process.env.API_ENDPOINT -- in this case, it was myapp.herokuapp.com

const myFunction = async(data) => {
  const request = host.concat('/postSomething');
  const res = await fetch(
    request,
    {
      body: JSON.stringify({
        variableA: data.variableA,
        variableB: data.variableB
      }),
      headers: {
        'Content-Type': 'application/json'
      },
      method: 'POST'
    }  
  );
  return await res.json();
}

【问题讨论】:

    标签: api express heroku vercel isomorphic-fetch-api


    【解决方案1】:

    显然,这只是我的 next.config.js 文件中的语法错误。 当我声明 API_ENDPOINT 时,我在“myapp.herokuapp.com”之前包含了“https://”,现在它可以工作了。

    【讨论】:

      猜你喜欢
      • 2021-08-10
      • 2019-11-19
      • 1970-01-01
      • 2017-07-06
      • 2021-02-12
      • 2017-12-06
      • 2021-06-23
      • 2015-12-04
      • 1970-01-01
      相关资源
      最近更新 更多