Created
October 10, 2022 14:43
-
-
Save lejonmanen/700a15722aacea06846f11ff5268b098 to your computer and use it in GitHub Desktop.
Express web server, minimal template
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Import packages, route middleware, and initialize app | |
import express, { Express, Request, Response } from 'express' | |
const app = express() | |
const port: number = 1337 | |
const pathToDist: string = 'dist' | |
// ---------------------------------------------------- | |
// Install any middleware before adding routes | |
// Important middleware: cors, static folders | |
// ---------------------------------------------------- | |
// Routes | |
// https://insomnia.rest/ strongly recommended for testing your API | |
app.get('/', (req: Request, res: Response) => { | |
// Remove this route after you have tested that the server works | |
res.send('Hello from server') | |
}) | |
app.get('/api/data', (req: Request, res: Response) => { | |
// Example API request handler. Typically we use | |
// the Express.Router middleware to group API routes | |
// in separate files | |
// https://expressjs.com/en/guide/using-middleware.html#middleware.router | |
let exampleData: string[] = ['example'] | |
res.send(exampleData) | |
}) | |
app.get('*', (req: Request, res: Response) => { | |
// Wildcard route catches all routes that haven't | |
// been caught previously. Send index.html to | |
// enable frontend routing, for example using | |
// React Router. | |
res.sendFile('path/to/dist/index.html') | |
}) | |
// ---------------------------------------------------- | |
// Finally start server | |
app.listen(port, () => { | |
console.log('Server is listening on port ' + port); | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
To add a static folder reliably in Node and Express, you need to calculate the correct path: