在next.js + Firebase托管PWA应用程序上获取Service-Worker时出现404错误

时间:2018-07-25 12:24:12

标签: reactjs firebase next firebase-hosting pwa

在next.js + Firebase托管PWA应用程序上获取服务工作者时出现404错误 我试图通过向此存储库中引入的next.js + firebase托管应用程序添加service-worker来制作PWA应用程序。 https://github.com/zeit/next.js/tree/canary/examples/with-firebase-hosting

但是,尽管可以运行到托管,但在运行service-worker.js时遇到了麻烦。

我认为原因是service-worker.js文件的路径,该文件位于dist / functions / next文件夹中。所以我尝试过变更通行证,但我解决不了。

Service worker registration failed, error1:  TypeError: Failed to register a ServiceWorker: A bad HTTP response code (404) was received when fetching the script.

有什么办法解决这个问题吗? 下面是functions / index.js文件。

const functions = require('firebase-functions');
const next = require('next');
import * as admin from 'firebase-admin';
const { join } = require('path');
const { parse } = require('url');
const express = require('express');

const routes = require('./routes');

// Region hosting next.js to cloud function

const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev, conf: { distDir: 'next' } });
const handle = routes.getRequestHandler(app);

const server = express();
server.get('*', (req, res) => handle(req, res));
server.get('/service-worker', (req, res) => {
  // try change pass but not worked
  // app.serveStatic(req, res, '_next/service-worker.js'),
  // app.serveStatic(req, res, 'next/service-worker.js');
  // app.serveStatic(req, res, '/service-worker.js');
  // app.serveStatic(req, res, '/next/service-worker.js');

  const filePath = join(__dirname , 'service-worker.js')
  app.serveStatic(req, res, filePath);
});

exports.next = functions.https.onRequest((req, res) => {
  console.log('File: ' + req.originalUrl); // log the page.js file that is being requested

  return app.prepare().then(() => {
    server(req, res);
  });
});

2 个答案:

答案 0 :(得分:1)

我解决了这个问题。 我失败的原因是server.get方法的顺序,这意味着首先我应该先编写server.get('/ service-worker'),然后再编写servet.get(*)。 并且,将文件路径从join(__ dirname,'service-worker.js')更改为'next / service-worker.js')

答案 1 :(得分:0)

https://github.com/hanford/next-offline似乎是next.js进行PWA的推荐方法。在构建应用程序时,您需要指示工作箱将生成的service-worker.js放在公共目录中。

这是next.config.js的示例:

const withOffline = require('next-offline')
const config = {
  workboxOpts: {
    swDest: '../public/service-worker.js',
  },
    // rest of your config
}
module.exports = withOffline(config)