ejs 文件 express 中未定义的导航器

Navigator undefined in ejs file express

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

<%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)

ejs-模板在您的节点服务器上呈现,其中不存在对 navigator(或 window)的引用。但是,您可以做的是将上述代码包含在 <script> 标签中,并 return 将其包含在您的模板中:

// 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>