Starting Node.js server w/ Gulp “connect” breaks o

2019-05-23 23:11发布

I'm trying to solve a problem that's been bugging me for awhile.

The Scenario:

The problem is when I use Gulp to start up my local server w/ Live Reload. It starts up my Angular app just fine, but when I make a file change Live Reload (page refreshes) breaks my app and gives me a "CANNOT GET" because my server.js (node server) file has a special way that it redirects the user to my "index.html" file. The reason for this is because I have "HTML5 mode" enabled in the Angular app (for pretty URL's) and I have to specify this in the server.js file for it to properly work.

Before I turned "html5 on" inside my angular app everything worked fine, but because of the special redirecting my Gulp.js file isn't written correctly to be aware of this.

If I run "node server.js" however, the angular app works as expected and gets page refreshes, it's just irritating to have this problem when I'm developing.

Questions:

  • How can I write my gulpfile.js to run the server.js file correctly?
  • Is there a better way to write my server.js file?
  • Is it possible run multiple ports at once (development mode and production mode)?


(I've left out a few folders and files to make it easier on the eyes)

File Structure:

ROOT

  • build (angular production app)
  • front (angular development app)
  • gulpfile.js (task runner)
  • server.js (node server)


Server.js (node server)

var express = require('express');
var app = express();

app.use('/js', express.static(__dirname + '/front/js'));
app.use('/build', express.static(__dirname + '/../build'));
app.use('/css', express.static(__dirname + '/front/css'));
app.use('/images', express.static(__dirname + '/front/images'));
app.use('/pages', express.static(__dirname + '/front/pages'));

app.all('/*', function(req, res, next) {

    // Sends the index.html for other files to support HTML5Mode
    res.sendFile('/front/index.html', { root: __dirname });
});

var port = process.env.PORT || 8000;
app.listen(port);


Gulpfile ("connect" starts on line 67)

var gulp          = require ('gulp'),
    sync          = require ('browser-sync'),
    bower         = require ('gulp-bower'),
    htmlify       = require ('gulp-minify-html'),
    uglify        = require ('gulp-uglify'),
    prefix        = require ('gulp-autoprefixer'),
    minify        = require ('gulp-minify-css'),
    imgmin        = require ('gulp-imagemin'),
    rename        = require ('gulp-rename'),
    concat        = require ('gulp-concat'),
    inject        = require ('gulp-inject'),
    connect       = require ('gulp-connect'),
    open          = require ('gulp-open');

// Bower Task
gulp.task('bower', function() {
    return bower()
      .pipe(gulp.dest('front/js/vendors'));
});

// HTML Task
gulp.task('html', function(){
    gulp.src('front/**/*.html')
      .on('error', console.error.bind(console))
      .pipe(gulp.dest('build'))
      .pipe(connect.reload());
});

// Styles Task (Uglifies)
gulp.task('styles', function(){
    gulp.src('front/**/*.css')
      .pipe(minify())
      .on('error', console.error.bind(console))
      .pipe(gulp.dest('build'))
      .pipe(connect.reload());
});

// Scripts Task (Uglifies)
gulp.task('scripts', function(){
    gulp.src('front/**/*.js')
      .pipe(uglify())
      .on('error', console.error.bind(console))
      .pipe(gulp.dest('build'))
      .pipe(connect.reload());
});

// Image Task (compress)
gulp.task('images', function(){
    gulp.src('front/images/*')
      .pipe(imgmin())
      .pipe(gulp.dest('build/images'))
      .pipe(connect.reload());
});

// Connect Task (connect to server and live reload)
gulp.task('connect', function(){
    connect.server({
      root: 'front',
      livereload: true
    });
});

// Watch Task (watches for changes)
gulp.task('watch', function(){
    gulp.watch('front/*.html', ['html']);
    gulp.watch('front/js/*.js', ['scripts']);
    gulp.watch('front/css/*.css', ['styles']);
    gulp.watch('front/images/*', ['images']);
});

// Open Task (starts app automatically)
gulp.task("open", function(){
  var options = {
    url: "http://localhost:8080",
    app: "Chrome"
  };
  gulp.src("front/index.html")
  .pipe(open("", options));
});

gulp.task('default', ['html', 'styles', 'scripts', 'images', 'connect', 'watch', 'open']);



Angular app

// App Starts
angular
    .module('app', [
        'ui.router',
        'ngAnimate',
        'angular-carousel'
    ])
    .config(['$urlRouterProvider', '$stateProvider', '$locationProvider', function($urlRouterProvider, $stateProvider, $locationProvider) {
        $urlRouterProvider.otherwise("/");

        $stateProvider
            // Home Page
            .state('home', {
                url: '/',
                templateUrl: 'pages/home.html',
                controller: 'homeCtrl'
            })

        // use the HTML5 History API
        $locationProvider.html5Mode(true);
    }])



Index.html

    <!DOCTYPE html>
    <html class="no-js" ng-app="app" ng-controller="mainCtrl">
    <head>
        <title>Website</title>
        <meta charset="utf-8"/>

        <!-- Universal Stylesheets -->
        <link href="css/stylesheet.css" type="text/css" rel="stylesheet" />
        <!-- Sets base for HTML5 mode -->
        <base href="/"></base>
    </head>

    <body>
      <section class="row main" ui-view></section>

        <!-- Javascript -->
        <script src="js/scripts.js"></script>
    </body>

    </html>

Thanks in advance for your help!

1条回答
走好不送
2楼-- · 2019-05-23 23:20

Here is a fairly good solution :)

Here is what you should use:

gulp.task('connect', connect.server({
  root: ['build'],
  port: 9000,
  livereload: true,
  open: {
    browser: 'Google Chrome'
  },
   middleware: function(connect, opt) {
      return [ historyApiFallback ];
    }
}));

This is the module i use for SPA development:

"connect-history-api-fallback": "0.0.5",

Also AngularJs has a neat solution for avoiding setting base href

$locationProvider.html5Mode({enabled: true, requireBase: false})
查看更多
登录 后发表回答