如果Service Worker需要html与servive_worker.js放在同一文件夹中,我该如何使用EJS(需要Views文件夹)?

时间:2018-10-22 18:23:30

标签: javascript node.js web-services ejs http-caching

我有一个非常简单的Web应用程序,可以练习使服务人员继续工作。我遇到的问题是我正在使用EJS,而EJS要求html保留在Views文件夹中。要缓存HTML,我必须将Service Worker JS文件与HTML放在同一位置-但是如果这样做,它将失败!我收到一条错误消息,指出HTML必须位于EJS视图文件中

如果我将HTML移到视图中,则不会收到错误,但是Service Worker不会缓存任何内容!

请有人可以建议我吗?

这是我当前的文件夹结构,服务工作人员不会在其中出错,但也不会缓存任何内容:

enter image description here

我将EJS文件放到哪里缓存?显然,它需要使用自己的文件夹来保存HTML

这是我的server.js:

const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const request = require('request');
const apiKey = '<api key>';

app.use(express.static('public'));
app.use(bodyParser.urlencoded({ extended: true }));

app.set('view engine', 'ejs');


app.get('/', function (req, res) {
  res.render('weather_html');
})

app.post('/', function (req, res) {
  let city = req.body.city;
  let url = `http://api.openweathermap.org/data/2.5/weather?q=${city}&units=metric&appid=${apiKey}`
request(url, function (err, response, body) {
    if(err){
      res.render('weather_html', {weather: null, error: 'Error, please try again'});
    } else {
      let weather = JSON.parse(body)
      if(weather.main == undefined){
        res.render('weather_html', {weather: null, error: 'Error, please try again'});
      } else {
        let weatherText = `It's ${weather.main.temp} degrees in ${weather.name}!`;
        res.render('weather_html', {weather: weatherText, error: null});
      }
    }
  });
})

app.listen(3000, function () {
  console.log('server is listening on port 3000!')
});

这是混蛋service_worker.js文件:

const filesToCache = [
  '/'
];

const staticCacheName = 'this is the SW\'s cache';

self.addEventListener('install', event => {
  console.log('Attempting to install service worker and cache whatever is in filesToCache');
  event.waitUntil(
    caches.open(staticCacheName)
    .then(cache => {
      return cache.addAll(filesToCache);
    })
  );
});

self.addEventListener('fetch', event => {
  console.log('Fetch event for ', event.request.url);
  event.respondWith(
    caches.match(event.request)
    .then(response => {
      if (response) {
        console.log('Found ', event.request.url, ' in cache');
        return response;
      }
      console.log('Network request for ', event.request.url);
      return fetch(event.request)

      .then(response => {

  return caches.open(staticCacheName).then(cache => {
    cache.put(event.request.url, response.clone());
    return response;
  });
});

    }).catch(error => {

    })
  );
});

我的EJS / HTML:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Test weather app</title>
    <link rel="stylesheet" type="text/css" href="/css/style.css">
    <link href='https://fonts.googleapis.com/css?family=Open+Sans:300' rel='stylesheet' type='text/css'>
  </head>
  <body>
    <p>Test weather search app</p>
    <img src="https://ichef.bbci.co.uk/news/660/cpsprodpb/AECE/production/_99805744_gettyimages-625757214.jpg">
    <div class="container">
      <fieldset>
        <form action="/" method="post">
          <input name="city" type="text" class="ghost-input" placeholder="Enter a City" required>
          <input type="submit" class="ghost-button" value="Enter a city name for temperature in celsius">
        </form>
        <% if(locals.weather !== null){ %>
          <p><%= locals.weather %></p>
        <% } %>

        <% if(locals.error !== null){ %>
          <p><%= locals.error %></p>
        <% } %>
    </fieldset>
    </div>
  <!-- Service Worker - Checks if the browser supports a service worker, if so, registers the file server_worker.js as the SW, then logs to console-->
  <script>
  if('serviceWorker' in navigator) {
    navigator.serviceWorker
             .register('/service_worker.js')
             .then(function() { console.log("Service Worker Registered"); });
  }
</script>
  </body>
</html>

这是使用当前文件夹结构的SW的屏幕截图,没有错误。我希望它能够将HTML缓存在views文件夹中:

enter image description here

1 个答案:

答案 0 :(得分:0)

您可以更改文件夹的结构,如下所示:

enter image description here

然后在server.js文件中进行创建,以便在公共文件夹中引用静态文件(并将它们实际放置!):

app.use(express.static('public'));

另一个注意事项,我发现如果调用任何内容并返回404响应,则无法注册和安装SWW