Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.0k views
in Technique[技术] by (71.8m points)

angularjs - Angular HTML5 mode with express

I know there are answers to this question, but they're not fully working for me. I'm using Angular 1.4 and Express 4. Express is handling API calls and Angular is supposed to be handling all HTML.

My express app.js:

var express = require('express');
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

require('./routes/api')(app);

var app = express();

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

app.use(express.static(path.join(__dirname, '../client')));
// This covers serving up the index page
app.use(express.static(path.join(__dirname, '../client/.tmp')));
app.use(express.static(path.join(__dirname, '../client/app')));

app.all('*', function(req, res) { 
  res.redirect('/index.html'); 
});

module.exports = app;

Here is angular app.js

angular
  .module('punyioApp', [
    'ngAnimate',
    'ngAria',
    'ngCookies',
    'ngMessages',
    'ngResource',
    'ngRoute',
    'ngSanitize',
    'ngTouch'
  ])
  .config(function ($routeProvider, $locationProvider) {
    $routeProvider
      .when('/', {
        templateUrl: 'views/main.html',
        controller: 'MainCtrl',
        controllerAs: 'main'
      })
      .when('/howitworks', {
        templateUrl: 'views/howitworks.html',
        controller: 'HowItWorksCtrl',
        controllerAs: 'howitworks'
      })
      .otherwise({
        redirectTo: '/'
      });

      $locationProvider.html5Mode(true);
  });

Now, if I go to http://localhost:3000/, I get the main Angular view, as expected. The problem is when I go to http://localhost:3000/howitworks, which redirects me to http://localhost:3000/index.html and does not show the 'howitworks' view. How do I fix the express router so that I can go to http://localhost:3000/howitworks ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your code is simply redirecting every request to index.html, which isn't what you want. You do need that file, but since Angular handles the routing, you only want Express to send the file, no questions asked.

Basically, you shouldn't be using redirect, but sendFile:

app.get('/*', function(req, res) { 
  res.sendFile(__dirname + '/index.html')
});

Also, as someone pointed out in the comments, you should use get and not all.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...