We can access the req and res objects when the asyncData method is executed on the server side. They contain useful information of the HTTP request sent from the user. But we should always check with an if condition before accessing them:
// pages/index.vue
<p>{{ host }}</p>
export default {
asyncData ({ req, res }) {
if (process.server) {
return { host: req.headers.host }
}
return { host: '' }
}
}
In the preceding code, we use the if condition to make sure that the asyncData method is called on the server side before obtaining the information of the request headers. These two objects are unavailable on the client side, so you will get undefined when accessing them on the client side. So the result we will get from the preceding code is localhost:3000 when the page is loaded on the browser for the first time, but you will not see that piece of information again when revisiting this page by the route generated from the <...