Navigator undefined in ejs file express

会有一股神秘感。 提交于 2021-01-28 14:10:59

问题


I want to get the latitude and longitude of the user's location. In the ejs file I am getting error navigator undefined.Can somebody please help?Thanks in advance.

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

Updated code:

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

回答1:


The ejs-template is rendered on your node-server, where no reference to navigator (or window for that matter) exists. What you can do, however, is to include above code in a <script>-tag and return this in your template:

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


来源:https://stackoverflow.com/questions/62863560/navigator-undefined-in-ejs-file-express

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!