Node.js Tutorial: Build Server with Express.js
Node.js is a powerful JavaScript runtime that allows developers to build scalable server-side applications. In this tutorial, we will be focusing on using Express.js, a popular Node.js web application framework, to build a server for our application.
Prerequisites
- Basic knowledge of JavaScript
- Node.js installed on your machine
Setting up a new project
First, create a new directory for your project and navigate into it using the terminal or command prompt.
$ mkdir my-nodejs-app
$ cd my-nodejs-app
Next, run the following command to initialize a new Node.js project:
$ npm init -y
This will create a package.json file in your project directory with some default settings.
Installing Express.js
Now, let’s install Express.js by running the following command:
$ npm install express
This will download and install Express.js and add it to your project’s dependencies in the package.json file.
Creating a server with Express.js
Now that we have Express.js installed, let’s create a simple server in a new file named server.js:
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Hello, World!');
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
This code creates a new Express.js app, sets up a route to handle requests to the root URL (‘/’), and starts the server on port 3000.
Running the server
To start the server, run the following command in your terminal:
$ node server.js
You should see a message in the terminal indicating that the server is running on port 3000. You can now open a web browser and navigate to http://localhost:3000 to see your server in action.
Conclusion
Congratulations! You have successfully built a server with Express.js in Node.js. This is just the beginning of what you can accomplish with Node.js, so feel free to explore more advanced features and tutorials to take your skills to the next level.