ExpressJS Boilerplate (Hybrid App with API and SPA support)

JS
S
JavaScript

Boilerplate for a Node.js Express backend app with /api/ and SPA static file support

1// app.js
2const express = require('express');  
3const app = express();  
4const path = require('path');  
5const bodyParser = require('body-parser');
6
7app.use(bodyParser.json());  
8app.use(bodyParser.urlencoded({ extended: false }));
9
10/**
11 * API
12 */
13app.get('/api', function(req, res, next) {  
14    let data = {
15        message: 'Hello World!'
16    };
17    res.status(200).send(data);
18});
19app.post('/api', function(req, res, next) {  
20    let data = req.body;
21    // query a database and save data
22    res.status(200).send(data);
23});
24
25/**
26 * STATIC FILES
27 */
28app.use('/', express.static('app'));
29
30// Default every route except the above to serve the index.html
31app.get('*', function(req, res) {  
32    res.sendFile(path.join(__dirname + '/app/index.html'));
33});
34
35module.exports = app;  

Created on 5/22/2018