In this tutorial, we aim to help you set up your first Express.js application. By the end of this tutorial, you will have a functioning Express.js server running on your local machine.
You will learn how to:
Before you start, ensure that you have Node.js and npm (Node Package Manager) installed on your machine.
Express.js is a framework for Node.js, so to use it, we need to have Node.js installed. If you don't have Node.js, you can download it from here. After installing Node.js, we can install Express.js using NPM (Node Package Manager) with the following command:
npm install express --save
In Express.js, creating a server is as easy as calling a function. We can create a new file named app.js and write the following code:
// This line imports Express into our application
var express = require('express');
// We then use it to create our app
var app = express();
// Define a route at the root path (/)
app.get('/', function(req, res) {
res.send('Hello World!');
});
// Finally, we start the server
var server = app.listen(3000, function() {
console.log('Server is running on http://localhost:3000');
});
Here's a step-by-step walkthrough of creating a "Hello World" server with Express:
// Step 1: Import Express.js
var express = require('express');
// Step 2: Initialize the application
var app = express();
// Step 3: Define a GET route for the root path ("/")
app.get('/', function(req, res) {
// This function will be called when a GET request is made to the root path
// It sends the string 'Hello World!' as a response
res.send('Hello World!');
});
// Step 4: Start the server
var server = app.listen(3000, function() {
// This function is called when the server starts successfully
console.log('Server is running on http://localhost:3000');
});
When you run this program and navigate to http://localhost:3000 in your browser, you should see the text 'Hello World!'.
In this tutorial, we installed Express.js, set up a simple server, and defined a route that responds with 'Hello World!'. This is the very basics of creating web applications with Express.js.
Modify the application so that it responds with 'Hello Express!' instead of 'Hello World!'.
Solution:
app.get('/', function(req, res) {
res.send('Hello Express!');
});
Add a new route '/hello' that responds with 'Hello from route!'.
Solution:
app.get('/hello', function(req, res) {
res.send('Hello from route!');
});
For further practice, consider exploring more about Express.js by reading its official documentation. You can also try building a more complex application with multiple routes, middleware, and error handlers. Happy coding!