To start, create a file named app.js
in your project directory. Here’s how to set up a basic Express server:
Step 1: Import Express
First, you’ll need to require Express in your app.js
file:
const express = require('express');
Step 2: Create an Express Application
Call the express()
function to create an application instance:
const app = express();
Step 3: Define the Port
Specify the port your application will listen on. Let’s use port 3000:
const port = 3000;
Step 4: Start Listening
Use the listen
method on the app instance to start the server. Provide the port and a callback function to display a message when the server starts:
app.listen(port, () => {
console.log(`Express server is listening on port ${port}`);
});
Full Code for app.js
Here’s the complete code:
const express = require('express');
const app = express();
const port = 3000;
app.listen(port, () => {
console.log(`Express server is listening on port ${port}`);
});
Running the Server
- Open your terminal and navigate to your project directory.
- Run the following command to start the server:
node app.js
- You should see the message:
Express server is listening on port 3000
Accessing the Server
Open your browser or any API client and navigate to:
http://localhost:3000
Currently, there are no routes defined, so you won’t get much response. In the next section, we’ll define routes to handle requests.
What’s Next?
In the next lesson, we’ll learn how to create routes to handle incoming requests and return appropriate responses. Stay tuned!