,

Setting up server #1 for Express JS REST API

Posted by


In this tutorial, we will be discussing how to set up an Express JS server for building a RESTful API. Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications.

Step 1: Install Node.js and Express

Before we can get started with building our REST API server, we need to have Node.js and Express installed on our machine. To do this, you can go to the Node.js website (https://nodejs.org) and download the latest version of Node.js. Once you have installed Node.js, you can use npm to install Express by running the following command in the terminal:

npm install express

Step 2: Setting up the project structure

Now that we have Node.js and Express installed, we can start setting up our project structure. Create a new directory for your project and navigate into that directory in your terminal. Inside the project directory, create a new file called server.js where we will define our Express server.

mkdir express-rest-api
cd express-rest-api
touch server.js

Step 3: Setting up the Express server

In the server.js file, we will start by importing Express and creating a new instance of the Express app. We will also define a port number for our server to listen on.

const express = require('express');

const app = express();
const port = 3000;

app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});

Step 4: Implementing basic routes

Now that we have our Express server set up, we can start implementing some basic routes for our REST API. Let’s create a simple route to retrieve a list of users:

const users = [
  { id: 1, name: 'John Doe' },
  { id: 2, name: 'Jane Smith' },
];

app.get('/users', (req, res) => {
  res.json(users);
});

Now, if you run your server (node server.js) and navigate to http://localhost:3000/users in your browser, you should see the list of users being returned as JSON.

Step 5: Adding CRUD operations

To make our REST API more robust, let’s add CRUD (Create, Read, Update, Delete) operations for managing users. We will define routes for creating a new user, updating an existing user, and deleting a user:

app.post('/users', (req, res) => {
  const newUser = req.body;
  users.push(newUser);
  res.json(newUser);
});

app.put('/users/:id', (req, res) => {
  const userId = parseInt(req.params.id);
  const updatedUser = req.body;
  users.forEach((user, index) => {
    if (user.id === userId) {
      users[index] = updatedUser;
    }
  });
  res.json(updatedUser);
});

app.delete('/users/:id', (req, res) => {
  const userId = parseInt(req.params.id);
  const index = users.findIndex(user => user.id === userId);
  if (index !== -1) {
    users.splice(index, 1);
  }
  res.sendStatus(204);
});

Step 6: Handling middleware

Middleware functions in Express are functions that have access to the request and response objects. You can use middleware to perform operations before or after a route handler is executed. For example, let’s add a middleware function that logs the request method and URL to the console for each incoming request:

app.use((req, res, next) => {
  console.log(`${req.method} ${req.url}`);
  next();
});

Step 7: Error handling

It’s important to include error handling in your Express server to handle any unexpected errors that may occur. You can create a custom error handler middleware function to catch errors and send an appropriate response back to the client:

app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).send('Something broke!');
});

Step 8: Conclusion

Congratulations! You have successfully set up an Express JS server for building a RESTful API. In this tutorial, we covered setting up the project structure, defining routes for basic and CRUD operations, handling middleware, and error handling. You can now continue to build out your REST API by adding more routes and functionalities as needed. Happy coding!

0 0 votes
Article Rating

Leave a Reply

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@กิตติพิชญ์ฐานพัฒนากิจ
2 hours ago

ฟังเพลินมากก

1
0
Would love your thoughts, please comment.x
()
x