简体   繁体   English

Next.JS - 为什么在服务器端和客户端都发生数据获取?

[英]Next.JS - Why is data fetching happening both in server and client side?

I'm calling a normal fetch function in index.js component and then logging the response to the console.我在index.js组件中调用一个普通的 fetch 函数,然后将响应记录到控制台。 Despite the fetch is inside component function, the response is logged in server side too: It appears in the terminal, which makes me believe that data fetching is done from server side as well.尽管fetch在组件函数内部,但响应也记录在服务器端:它出现在终端中,这让我相信数据获取也是从服务器端完成的。

Why is that happening ?为什么会这样?

The code inside pages/index.js : pages/index.js里面的代码:

export default function Home() {

  fetch('http://localhost:3000/api/hello').then(res=>res.text()).then(data=>console.log(data));

  return (
    <div>
      Home
    </div>
  )
}

The code inside pages/api/hello.js : pages/api/hello.js里面的代码:

import connectDB from "../../middleware/mongodb";

async function handler (req,res) {
  res.end('Hello');
}

export default connectDB(handler);

My VS Code terminal after I open http://localhost:3000 :打开http://localhost:3000后我的 VS Code 终端:

在此处输入图像描述

Next.js runs your component functions both on the server, and on the client. Next.js 在服务器和客户端上运行您的组件功能。 The reason it is run on the server is to generate the HTML being sent to the client.它在服务器上运行的原因是生成发送到客户端的 HTML。

You can use typeof window to check if you are in the browser or on the server, which is currently the recommended approach .您可以使用typeof window来检查您是在浏览器中还是在服务器上,这是目前推荐的方法

export default function Home() {

  if (typeof window === 'undefined') {
    // Only run on server
    fetch('http://localhost:3000/api/hello').then(res=>res.text()).then(data=>console.log(data));
  }

  if (typeof window !== 'undefined') {
    // Only run in browser
    fetch('http://localhost:3000/api/hello').then(res=>res.text()).then(data=>console.log(data));
  }

  return (
    <div>
      Home
    </div>
  )
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM