Zane Hitchcox Zane Hitchcox - 3 months ago 18
AngularJS Question

How do I always serve the same file with express?

Is there any way I can always serve the same file?

So, if they go to website.com/ajsdflkasjd it still serves the same file as website.com/asdnw

I would like to do this using express with node.

The file I have is a static html file, not a jade file.

By the way, the reason I'm wanting to do this, in case you were wondering, is I have an angularjs app that handles all the routing for me. So, all I need to do is serve that one page, and it will take care of the rest.

Thanks in advance!

Answer

new answer

const app= require('express')()
     // static file serve
     app.use(express.static(__dirname))
     // not found in static files, so default to index.html
     app.use((req, res) => res.sendFile(`${__dirname}/index.html`))
app.listen(3000)

old answer

var express = require('express');
var bodyParser = require('body-parser')
var path = require('path')
var app = express();
     // url encoding
     app.use(bodyParser.urlencoded({extended:false}));
     // gzip
     // redirect all html requests to `index.html`
     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.listen(3000)