Express Webserver
Overview
The express library is a Javascript library designed to provide tools for hosting a webserver.
data desktop
Setup
The only requirement
npm install express
Serving Files
If you want your server to serve static files from a specified folder on the hard drive, include the
following code.
app.use(express.static(path.join(__dirname, 'public'), { maxAge: 100000 }));
The max age parameter tells the system how long to cache files (in milliseconds) before checking for updates.
Javascript Serer
// app.js
const express = require('express');
const app = express();
const PORT = process.env.PORT || 3000;
const path = require('path');
//uncomment this if you want to serve files
//app.use(express.static(path.join(__dirname, 'public'), { maxAge: 100000 }));
// Middleware to parse incoming JSON payloads
app.use(express.json());
// HTTP GET route for the root path
app.get('/', (req, res) => {
res.send('Hello World!');
});
// HTTP GET route with a URL parameter
//The :id in your code is only a placeholder in Express, meaning the actual URL requested should look like /api/users/123
app.get('/api/users/:id', (req, res) => {
const userId = req.params.id;
res.json({ message: `Fetching data for user ${userId}`, status: 'success' });
});
// HTTP POST route to receive data
app.post('/api/data', (req, res) => {
const receivedData = req.body;
res.status(201).json({
message: 'Data successfully received',
data: receivedData
});
});
// Start the server and listen on the specified port
app.listen(PORT, () => {
console.log(`Server is running at http://localhost:${PORT}`);
});