js中检测到我在服务器还是客户端上

js中检测到我在服务器还是客户端上

本文介绍了我如何在Next.js中检测到我在服务器还是客户端上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我正在将客户快递服务器与Next.js一起使用.它在容器内运行.我正在用isomorphic-fetch进行http请求以获取渲染的数据.我想在服务器上运行时执行localhost,而在客户端上运行时执行mysite.com.不确定实现此目的的最佳方法.我可以通过const isServer = typeof window === 'undefined'轻松地做到这一点,但这似乎很糟糕.

I am using a customer express server with Next.js. It's running within a container. I am doing an http request with isomorphic-fetch to get data for my render. I'd like to do localhost when running on server and mysite.com when running on client. Not sure the best way to accomplish this. I can do it hackily by doing const isServer = typeof window === 'undefined' but that seems pretty bad.

推荐答案

您可以使用process.browser来区分服务器环境(NodeJS)和客户端环境(浏览器).

You can use process.browser to distinguish between server environment (NodeJS) and client environment (browser).

process.browser在客户端上是true,在服务器上是undefined.

process.browser is true on the client and undefined on the server.

这篇关于我如何在Next.js中检测到我在服务器还是客户端上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 12:38