Skip to content

Instantly share code, notes, and snippets.

@lejonmanen
Created October 10, 2022 14:43
Show Gist options
  • Save lejonmanen/700a15722aacea06846f11ff5268b098 to your computer and use it in GitHub Desktop.
Save lejonmanen/700a15722aacea06846f11ff5268b098 to your computer and use it in GitHub Desktop.
Express web server, minimal template
// 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);
})
@lejonmanen
Copy link
Author

To add a static folder reliably in Node and Express, you need to calculate the correct path:

const __dirname = dirname(fileURLToPath(import.meta.url))
const pathToStaticFolder = join(__dirname, 'your-folder-name')
app.use( express.static(pathToStaticFolder) )

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment