Angular 5服务工作者不使用Express

时间:2018-02-02 16:02:41

标签: node.js angular express service-worker angular-service-worker

所以在2天的时间里,我的Angular5服务工作者遇到了一些麻烦,但我认为我已经将其缩小到了我服务应用程序的方式。您可以在from this SO question I posted详细了解我是如何达到这一点的,或者您可以阅读摘要:

服务工作者在从http服务器运行我的应用程序时工作,但在我使用节点来提供快速应用程序时则不行。

我现在看到的主要问题是,当我使用node / express应用程序为我的应用程序提供服务时,我的开发工具中的网络选项卡在我的网络离线时为localhost:3000提供了504状态。就好像服务工作者没有指向localhost:3000 / index.html。但是,在为http-server提供文件时,这不是问题。

这是我的server.js文件,我有节点用来为我的角应用程序提供服务:

const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const http = require('http');
const favicon = require('serve-favicon');
const logger = require('morgan');
const app = express();
const cookieParser = require('cookie-parser')
const bluebird = require('bluebird')


// Parsers
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(logger('dev'));

// Angular DIST output folder
app.use(express.static(path.join(__dirname, 'dist')));


// Send all other requests to the Angular app
app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname,'dist/index.html'));
});

// catch 404 and forward to error handler
app.use(function(req, res, next) {
 var err = new Error('Not Found');
 err.status = 404;
 next(err);
});

// error handler
app.use(function(err, req, res, next) {
 // set locals, only providing error in development
 res.locals.message = err.message;
 res.locals.error = req.app.get('env') === 'development' ? err : {};

 // render the error page
 res.status(err.status || 500);
 res.render('error');
});


// Set export
const port = process.env.PORT || '3000';
app.set('port', port);

const server = http.createServer(app);

server.listen(port, () => console.log(`Running on localhost ${port}`));

有没有人知道为什么会这样?

额外信息

  1. 我使用标签--service-worker启动了我的角度应用程序,如angular docs所述,没有额外的自定义。
  2. 没有控制台错误。唯一的错误是网络选项卡中的504状态。
  3. 在这两种情况下,都会安装一个服务工作者,并且缓存所有应该缓存的文件。
  4. 如果您想亲自测试一下: 1.下载此测试仓库here。 2.运行npm install。然后运行ng build --prod。 3.测试http-server运行npm install http-server。导航到dist文件夹并运行http-server -p 4200。 4.要测试快速服务器,请导航到根目录并运行node server.js

    更新

    (抱歉我的缺席,我有真正的工作需要照顾,但我已经准备用新的想法来解决问题了)

    我注意到如果我通过检查dev-tools上的离线按钮来模拟服务器处于脱机状态,那么运行我的服务器的控制台仍会收到请求。但是,当我检查devtools中的网络工具栏时,它表示服务工作者正在提供这些请求。这些请求尝试提供我的后台文件但是失败了504找不到错误,只提取了index.html文件和元素文件中的图片。此外,这些请求仅在导航到其他页面后才起作用,从不在刷新之后。

    如果我在终端中关闭服务器,服务工作者只会尝试从服务工作者那里获取localhost3000,但这会因504错误而失败。屏幕上不显示任何其他内容,除了更新的服务工作文件外,网络选项卡不会发出任何其他请求。

    我不知道如何对这些发现做出什么,并再次感谢任何帮助

1 个答案:

答案 0 :(得分:0)

快速猜测,但尝试console.log(path.join(__dirname,'dist/index.html'))

我相信你会得到/your/project/dirdist/index.html。您错过了/

尝试:

path.join(__dirname,'/dist/index.html')

所以你得到:

/your/project/dir/dist/index.html

相关问题