Навигатор не определен в e js файл express - PullRequest
1 голос
/ 12 июля 2020

Я хочу получить широту и долготу местоположения пользователя. В файле e js я получаю ошибку навигатора undefined. Может ли кто-нибудь помочь? Заранее спасибо.

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

1 Ответ

2 голосов
/ 12 июля 2020

Шаблон ejs отображается на вашем сервере-узле, где нет ссылки на navigator (или window в этом отношении). Однако вы можете включить приведенный выше код в тег <script> и вернуть его в свой шаблон:

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