When I call a regular fetch function in the index.js
component and then log the response to the console, something unexpected happens. Despite the fetch being inside the component function, the response is also logged on the server side: it shows up in the terminal. This led me to believe that data fetching is somehow being done from both the client and server sides.
Why is this occurring?
The code within 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 within pages/api/hello.js
:
import connectDB from "../../middleware/mongodb";
async function handler (req,res) {
res.end('Hello');
}
export default connectDB(handler);
In my VS Code terminal after opening http://localhost:3000
: