【问题标题】:Getting error while testing for geolocation in the browser在浏览器中测试地理位置时出错
【发布时间】:2021-04-17 08:35:36
【问题描述】:

我正在尝试在我的应用中使用地理定位 API。幸运的是,我在MDN website 找到了我想使用的一个,但是当我尝试测试地理定位对象(如果它存在于浏览器中)时,我收到了这个错误:

服务器错误
ReferenceError: 导航器未定义

生成页面时发生此错误。任何控制台日志都将显示在终端窗口中。
源页面/index.js (24:20) @eval

  22 | }
  23 | 
> 24 | if('geolocation' in navigator) {
     |                    ^
  25 |   console.log('It does exist')
  26 | } else {
  27 |   console.log('doesn't exist')

这是我尝试实现的代码(来自 MDN 文档网站):

if('geolocation' in navigator) {
  /* geolocation is available */
} else {
  /* geolocation IS NOT available */
}

你能告诉我我做错了什么,以及如何解决它吗?

【问题讨论】:

  • 你在使用 React 吗?
  • 这是否在服务器上执行(Server Error“任何控制台日志都将显示在终端窗口中”)?
  • @showdev 是的,先生。准确地说是下一个JS。这会是问题吗?
  • @ChrisBBB 你在本地测试吗? (如 localhost:port} 因为它在HTTP 连接中不起作用,只能在HTTPS 协议中起作用。This feature is available only in secure contexts (HTTPS).

标签: javascript reactjs geolocation next.js


【解决方案1】:

服务器上没有window 对象。当您想使用 window 对象时,您需要在 client 端进行。所以在你的 react 组件中,你需要使用useEffect,因为这个函数只在浏览器中运行。

useEffect(()=>{
  if('geolocation' in navigator) {
    /* geolocation is available */
  } else {
    /* geolocation IS NOT available */
  }
},[])

useEffect里面的函数会在组件挂载到浏览器时运行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-31
    • 1970-01-01
    • 2013-09-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多