How To Create Basic Expressjs App?
Setting up Express.js is a straightforward process. Follow these steps to get started:
Prerequisites:
Node.js: Ensure you have Node.js installed on your system. You can download and install it from the official Node.js website.
Steps to Set Up Express.js:
1- Create a Project Directory:
Create a new directory for your Express.js project using the terminal or command prompt.
mkdir my-express-app cd my-express-app
2- Initialize Node.js Project:
Initialize a new Node.js project in your project directory using npm (Node Package Manager). This will create a package.json file.
npm init -y
Install Express.js:
Install Express.js as a dependency for your project using npm.
npm install express
3- Create an Express Application:
Create a new JavaScript file (e.g., app.js) in your project directory. Import Express and create an instance of the Express application.
Paste the code below in the app.js file.
const express = require('express');
const app = express(); const port = 3000; // Port number to run the server
app.get('/', (req, res) => {
res.send('Hello, World!'); // Send a response when accessing the root URL
});
app.listen(port, () => {
console.log(`Server is running at http://localhost:${port}/`);
});
Run the Express Application:
Start your Express.js application by running the following command in the terminal:
Your Express.js server will start and listen for requests at http://localhost:3000/ (or the port you specified).
That's it! You've set up a basic Express.js application. You can now build routes, handle requests, and create a full-fledged web application using Express.js. Make sure to explore the official Express.js documentation to learn more about its features and capabilities.