This is my first blog post and this is your first node.js app.
Node.js is a backend javascript framework very popular that allow us to create a simple server or a simple rest service in 5 minutes or less (depends of your ability to type fast).
In this short post, I'll show you how to create a simple Rest Service Api.
Pre-Requirements:
Node.js
Some text editor: Visual Studio Code
So, lets start coding.
First of all, you need to create a directory for your node application.
Now, go to the directory that you just created and execute the next command to initiate the nodejs app.
This instruction will setup your project. The argument -Y means that you agree with all questions that the process do.
With the initiation completed, the package.json is created with the following information:
So far so good. Now, that you create the project, lets add some features. You can execute the following command to install express.
Express framework is the most popular framework for build robust node.js applications.
After that, if you open your project, you will see a new folder called "node_modules". This is all the dependencies of express framework.
Note: When you push your project to Github, I recommend you to create the ".gitignore" file. This file exists to indicate that some specific folder/file is not to push. So, the best pratice is not push the dependencies of express framework. To do that, open the .gitignore and type "node_module" in order to ignore this folder when you push the project.
Continuing our project, lets create the index.js file and add some magic stuff. This file is the entry point to the application.
As you can see, in index.js file we have some cool stuff.
In first line indicates that our project will depends of express framework. So, in order to access and use this framework, we need import it to our application. This is possible with require('module') where "module" is some stuff that you could find in NPM or in your own libraries.
The second line, we creates a variable called "app" that will be a representation of express framework. That means, that we need to use this app to access to express framework.
The next piece of code creates our server and as you can see the server is listening on port 3000.
So, if you open your web browser and type "http://127.0.0.1:3000/" that will be the result:
Well, the server just response with a classic "Hello World". Thats happen because, we code our server, our entry point the following way:
This code, creates our endpoint "/" and every time that the client sends a request
"http://127.0.0.1:3000/" will enter in this endpoint.
In next post, we go deeper in restful concepts and how works in node.js + express framework.
Top comments (0)