write expressjs example
- User
write expressjs example
- Assistant
Certainly! Here's a simple example of an Express.js server. This example sets up a basic server that handles a few HTTP routes:
- GET / - Returns "Hello World"
- GET /about - Returns "About Page"
- GET /users/:id - Returns a JSON object with user details based on the ID provided in the route.
javascript// Import the express module const express = require('express'); // Create an instance of express const app = express(); // Define a port number const port = 3000; // Define a route for the root URL ("/") app.get('/', (req, res) => { res.send('Hello World'); }); // Define a route for "/about" app.get('/about', (req, res) => { res.send('About Page'); }); // Define a route for "/users/:id" app.get('/users/:id', (req, res) => { const userId = req.params.id; res.json({ id: userId, name: `User ${userId}`, email: `user${userId}@example.com` }); }); // Start the server and listen on the specified port app.listen(port, () => { console.log(`Express server is running on http://localhost:${port}`); });Explanation
-
Import and Initialize: The code starts by importing the Express module and creating an application instance.
-
Routes: Different routes are defined for handling requests:
'/': This is the root route that responds with "Hello World".'/about': This route responds with "About Page".'/users/:id': A parameterized route that takes a user ID and responds with a JSON object representing that user.
-
Start Server: The application listens on port 3000. Once the server is started, you'll see a log message indicating where it's running.
How to Run
-
Make sure you have Node.js and npm installed on your system.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.