r/JavaScriptTips • • Feb 13 '23

How to serve a website/SPA with API using Node-Express 📁✨

Post image
12 Upvotes

2 comments sorted by

1

u/Low_Mammoth_9371 Feb 13 '23

Code to copy below, explanatory YT tutorial here: https://youtu.be/fyc-4YmgLu0

const express = require('express');
const path = require('path');
const app = express();
const port = 3000;

// Create API that supports a GET request:
app.get('/api', (req, res) => {
  res.json('HTTP GET request received');
})

// Attempt to serve file matching request:
app.use(express.static(path.join(__dirname, 'public')));
// (e.g. webpage, single-page application, simple file)

// 404 (runs if nothing above sent something already):
app.use((req, res) => {
  res.status(404);
  res.sendFile('Error 404: Resource not found');
});

// Start server:
app.listen(port, () => {
  console.log(`App listening  on port ${port}`);
});

1

u/[deleted] Feb 13 '23

Feel like nginx is gonna be a better answer here for this kind of thing...