Angular HTML5 mode with express

I know that there are answers to this question, but they do not fully work for me. I use Angular 1.4 and Express 4. Express handles API calls, and Angular should handle all the 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 view of Angular, as expected. The problem is that I go to http: // localhost: 3000 / howitworks , which redirects me to http: // localhost: 3000 / index.html and does not display the "howitworks" view. How to fix the express router so that I can go to http: // localhost: 3000 / howitworks ?

+4
source share
3 answers

Your code simply redirects each request to index.html , which you do not need. You need this file, but since Angular handles routing, you want Express to send the file, no questions asked.

Basically, you should not use redirect , but sendFile :

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

Also, as someone commented in the comments, you should use get , not all .

+12
source

If you use angilejs ui-router, you do not need to use express, you can use node-static or just nginx, and also use grunt or gulp to connect the plugin to dubug, I think it is better,

0
source

In case of jade, you can use:

 app.get('/*', function (req, res) { res.render('index.pug'); }); 
0
source

All Articles