【问题标题】:Navigator undefined in ejs file express在 ejs 文件中未定义导航器 express
【发布时间】:2020-07-13 18:14:05
【问题描述】:

我想获取用户所在位置的经纬度。在 ejs 文件中,我收到错误导航器未定义。有人可以帮忙吗?提前致谢。

<%if ('geolocation' in navigator) { console.log("geolocation supported"); } %>
<%else { console.log("Geolocation is not supported by this browser."); }%>

更新代码:

<html>
<head>
  <meta charset="utf-8">
  <title>Daily Journal</title>
  <meta charset="utf-8">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <link rel="stylesheet" href="/css/styles.css">
    </head>
   <body>
  <p>Testing</p>
    <div class="container">
    </div>
    <div class="footer-padding"></div>
      <div class="footer">
        <p>Made with ❤️ by The App Brewery</p>
      </div>
      <script>
        if ('geolocation' in navigator) {
            console.log("geolocation supported");
        } else {
            console.log("Geolocation is not supported by this browser.");
        }
    </script>
    </body>
    </html>
    ```
Error:
C:\Users\HP\Desktop\API-App\ejs-challenge\public\weather.js:2
  if ('geolocation' in navigator) {
ReferenceError: navigator is not defined
    at C:\Users\HP\Desktop\API-App\ejs-challenge\public\weather.js:2:24
    at Object.<anonymous> (C:\Users\HP\Desktop\API-App\ejs-challenge\public\weather.js:9:3)
    at Module._compile (internal/modules/cjs/loader.js:1156:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1176:10)
    at Module.load (internal/modules/cjs/loader.js:1000:32)
    at Function.Module._load (internal/modules/cjs/loader.js:899:14)
    at Module.require (internal/modules/cjs/loader.js:1042:19)
    at require (internal/modules/cjs/helpers.js:77:18)
    at Object.<anonymous> (C:\Users\HP\Desktop\API-App\ejs-challenge\app.js:6:15)
    at Module._compile (internal/modules/cjs/loader.js:1156:30)

【问题讨论】:

    标签: node.js express geolocation ejs


    【解决方案1】:

    ejs-模板在您的节点服务器上呈现,其中不存在对 navigator(或 window 的引用)的引用。但是,您可以将上述代码包含在 &lt;script&gt;-tag 中,然后在模板中返回:

    // your-template.ejs
    <h1>Hello EJS World </h1>
    
    <script>
        if ('geolocation' in navigator) {
            console.log("geolocation supported");
        } else {
            console.log("Geolocation is not supported by this browser.");
        }
    </script>
    

    【讨论】:

    • 嘿,谢谢你的回复!我试过你说的,我仍然得到同样的错误。导航器未定义
    • 你能添加更新的模板和确切的错误吗?
    • 是的。我在帖子中做到了。
    • 它现在可以工作了。非常感谢你!你保存了我的项目!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-14
    • 2020-11-14
    • 1970-01-01
    • 2018-12-03
    • 2018-09-25
    • 2017-05-02
    • 1970-01-01
    相关资源
    最近更新 更多