当它们需要来自第三方API的数据时,如何从next.js导出静态HTML页面?

I’m using next.js to build static HTML webpages.

One of my webpages needs data from a third-party API, which I’d like to fetch at build time and bake into the resulting HTML.

I don’t want this call to ever happen on the client, because:

  • CORS prevents the request from succeeding anyway
  • I would have to expose an API key on the client (no thank you)

I thought getInitialProps was the answer, because the fetched data is indeed baked in during the build/export process, but when I navigate away from the page and return from it, getInitialProps gets triggered on the client, breaking everything.

My current code in getInitialProps is something like:

static async getInitialProps(){
    // Get Behance posts
    const behanceEndpoint = `https://www.behance.net/v2/users/${process.env.BEHANCE_USERNAME}/projects?api_key=${process.env.BEHANCE_API_KEY}`
    const behanceRes = await fetch(behanceEndpoint)
    let behancePosts = await behanceRes.json()
    // Return only the required number of posts
    return {
        behancePosts: behancePosts
    }
}

有关如何处理此问题的任何建议或最佳做法?我知道Gatsby.js是开箱即用的。

宝儿阿飞Sam2020/03/24 17:32:47

一种可能是,如果您只想在服务器上执行一次以检查req参数是否在getInitialProps中:(文档req-HTTP请求对象(仅服务器)。

一种肮脏的方法:

  static async getInitialProps({ req }){
if (req) {
  // only executed on server
  // Get Behance posts
  const behanceEndpoint = `https://www.behance.net/v2/users/${process.env.BEHANCE_USERNAME}/projects?api_key=${process.env.BEHANCE_API_KEY}`
  const behanceRes = await fetch(behanceEndpoint)
  let behancePosts = await behanceRes.json()
  // Return only the required number of posts
  return {
      behancePosts: behancePosts
  }
} else {
  // client context
}

希望这会有所帮助。