Karim Tarabishy
Karim Tarabishy

Reputation: 1253

Handling Single Page App url routing

I want to have all requests return the index.html page which contains the front end app that will handle its own routing. Also I want that css/html/images/js are returned correctly so not to return index.html for all of these. So I have somthing like that in the server.js

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


app.use(express.static(path.join(__dirname,"app")));
app.get('*', function(req, res) {
    console.log(res);
    res.sendFile(path.join(__dirname, 'app', 'index.html')); // load the single view file (angular will handle the page changes on the front-end)
});


app.listen(5000);

Now If I type localhost:5000 I can get all the resources and every thing is okay. But if I make localhost:5000/something every resource I guess isn't found by express.static and is handled by the app.get(*,...) so all resources are returned as index.html.

So how can I have this kind of setup to work?!

Upvotes: 2

Views: 1989

Answers (2)

tikider
tikider

Reputation: 550

this is the right way to do it. read the comments.

var staticUrl = '/static';
var publicFolder = path.resolve(__dirname, '../public')//make sure you reference the right path

//serve all atatic files prefixed with '/static/*'
app.use(staticUrl, express.static(publicFolder));
app.use(staticUrl, function(req, res, next) {
  res.send(404); 
});

//serve index.html for all not 'static' prefixed requests
app.all('/*', function(req, res) {
  res.sendfile('index.html', {root: publicFolder});
});

Upvotes: 2

Shaun Xu
Shaun Xu

Reputation: 4656

This is the code I'm using in my Node.js + AngularJS project.

    app.use(function (req, res, next) {
        if (path.extname(req.path).length > 0) {
            // normal static file request
            next();
        }
        else {
            // should force return `index.html` for angular.js
            req.url = '/index.html';
            next();
        }
    });
    // static file serve
    app.use(express.static(__dirname + '/app'));

Upvotes: 0

Related Questions