Welcome back, through 2 posts in series about NodeJS on RPi, you know how to install the NodeJS and use NPM on RPi and is not any! In this article, I will guide you to a great thing that you certainly will not be able to do is Build a server back-end API on the RPi with NodeJS

If you have not read the previous two series of the review, you can see at:

Step 1: Project initiate

mkdir /home/pi/api
cd /home/pi/api
npm init

Step 2: Install necessary library

To be able to write the back-end API with NodeJS, we have a lot of ways and lots of libraries to support. However, in this article, I will guide you to use an extremely popular and well-known framework for programming the API, the web with NodeJS, which is Express.JS.

Install Express.JS is very simple, you just run the command line:

npm install express --save

Step 3: Let’s do it

nano server.js

Let’s code:

Code explanation: 

  1.  
  • Line 1: Declare the Express.JS library
  • Line 2: Create an app variable to create the route APIs later
  • Line 3: Declare the port the API service will run
  • Line 4: Creates an API service from the app variable
  • Lines 6-8: Create a GET route with the default address. This means that when you access localhost: 300, you will see Hello, Welcome to my NodePI.
  • Line 10-12: Create a POST route with the address localhost: 3000 / test. On this route, when you enter data into the body, the result is the body you entered
  • Lines 14-16: Initialize the server and send the server 3000 port

After running, you try to access the web and enter the address localhost: 3000 to see the results offline!

So you have a back-end server API already!

Hà Phương – Mechasolution.