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

reactjs React.js

Harry小卤蛋

2020-03-24

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是开箱即用的。

第3570篇《当它们需要来自第三方API的数据时,如何从next.js导出静态HTML页面?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

1个回答
宝儿阿飞Sam 2020.03.24

一种可能是,如果您只想在服务器上执行一次以检查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
}

希望这会有所帮助。

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android