top of page

Getting Started with Node.js

Writer's picture: CODING Z2MCODING Z2M

The "Getting Started with Node.js REST API with Express" app is designed for developers who are new to Node.js and want to learn how to build scalable web applications using the Express.js framework.

This app will cover the basics of Node.js, including its architecture, event-driven model, and non-blocking I/O. Participants will also learn how to use the Express.js framework to build simple REST API, including how to set up routes, handle HTTP requests and responses, and use middleware to improve application performance.

Participants will have the opportunity to understand how to get started and build a simple, scalable and high-performance REST API using Node.js and Express. They will learn how to use tools such as Postman / Thunder Client Rest API Client Extension for Visual Studio Code to test the REST API.

They will have gained practical experience with the tools and techniques necessary to build robust back-end systems, and be ready to start developing their own Node.js applications.


Basic steps to create a REST API in Node.js with Express

  1. Install Node.JS and NPM (Node Package Manager) on your system.

  2. Create a new directory for your project and navigate to it in the command line.

  3. Initialize a new Node.js project using the following command: npm init.

  4. Creating .gitignore file and ignore '/node_modules' and '.env' file

  5. Install the Express.js framework by running the following command: npm install express.

  6. Installing nodemon by running the following command: npm i -D nodemon

  7. Create a new file called server.js in your project directory.

  8. Add our 'start' script in package.json file with the following code. "start": "node server.js", "dev": "nodemon server.js"

  9. Running Server by running the following command: npm run dev

  10. Create '.env' file and Install 'dotenv' by running the following command: npm install dotenv

  11. Installing 'Thunder Client' extension in VS Code

  12. Import the Express.JS module and create an instance of the app using the following code:


​const express = require('express');
const app = express();

13. Define the routes for your API using the HTTP methods (GET, POST, PUT, DELETE) and the app instance. For example, here's how you can define a GET route that returns a JSON response:


​app.get('/api/users', (req, res) => {  
   const users = [
         { id: 1, name: 'John Doe' },
        { id: 2, name: 'Jane Doe' },
   ];
  res.json(users);
});


14. Start the server and listen for incoming requests using the app.listen() method:


​app.listen(3000, () => {
  console.log('Server started on port 3000');
  });



Example of Defining Routes & Using Middlewares in Express

In the code below, we first import the express library and create an instance of it called 'app'. We then set up middlewares using the app.use() method. We then set up our routes using the app.get() and app.post() methods. The first route responds to requests to the root URL with a "Hello World!" message. The second route uses a parameter in the URL to respond with the user ID that was passed in. The third route expects a JSON payload in the request body and responds with the name and email fields that were submitted.


​const express = require('express');
const app = express();

// Define a custom middleware function
const logger = (req, res, next) => {
  console.log(`${req.method} ${req.url}`);
    next();
};

// Using the custom middleware function with 'app.use' for all requests
   app.use(logger); 
// Using the pre-defined middleware function with 'app.use' to parse incoming request data as JSON and URL-encoded data.
   app.use(express.json());

/* Setting up error handling middleware using the app.use() - This will catch any errors that occur in our routes or middleware and respond with a 500 status code and a message */
app.use((err, req, res, next) => {   
    console.error(err.stack); 
    res.status(500).send('Something went wrong!'); 
});

// Routes
app.get('/', (req, res) => {
  res.send('Hello World!');
  });
  
  app.get('/users/:userId', (req, res) => {
    const { userId } = req.params;
      res.send(`User ID: ${userId}`);
 });
 
 app.post('/users', (req, res) => {
   const { name, email } = req.body;
     res.send(`Name: ${name}, Email: ${email}`);
 });

// Start the server and listen on port 3000 for incoming requests.
   app.listen(3000, () => {
     console.log('Server started on port 3000');
  });


72 views0 comments

留言


bottom of page