write expressjs example code
- User
write expressjs example code
- Assistant
Certainly! Below is a simple example of an Express.js application. This app demonstrates the basics, including setting up a server, defining routes for different HTTP methods, and sending responses to client requests.
First, make sure you have Node.js installed and then create a new directory for your project. Inside the project directory, initialize a new Node.js project and install Express using:
bashnpm init -y npm install expressNow, create a file called
app.jsand add the following code:javascript// Import the express module const express = require('express'); // Create an instance of an Express application const app = express(); // Define a port for the server to listen on const PORT = process.env.PORT || 3000; // Define a route for the root URL ("/") // This handles GET requests to the root URL app.get('/', (req, res) => { res.send('Hello, World!'); }); // Define another route for a different URL ("/about") // This handles GET requests to "/about" app.get('/about', (req, res) => { res.send('About Us'); }); // Define a route for handling POST requests ("/data") app.post('/data', (req, res) => { res.send('Data received'); }); // Start the server and have it listen on the specified port app.listen(PORT, () => { console.log(`Server is running on http://localhost:${PORT}`); });Here's a breakdown of what each section of the code does:
-
Import Express: We require the Express module which we've installed via npm.
-
Initialize Express: We create an instance of the Express application.
-
Define the Port: We set the port to an environment variable
PORTif available or default to 3000. -
Define Routes: We use
app.get()for defining GET request routes andapp.post()for defining POST request routes.
-