Making an API with Express
Enough theory, let's jump in and make a api with Express and Node.js. We will do this from scratch and I want you to follow along with this exercise, we will be explaining this and keep it as simple as possible.
Make sure you have the latest version of node.js installed in your system before we begin.
Initialising a node project & installing Express
Let's go to our file manager in our computer and create a new folder for our fresh new project. Open this folder in our terminal
Once done, type
npm init in your terminal and run the command. This will open the Node project CLI which initializes a project for us. Add in some information like your project name, description author. You can leave the test command, git repository & keywords blank.
Enter yes and this will quickly initialise your project. You will notice that a
package.json file is generated in your project folder.
package.json is like a identity card of your project, it contains all the metadata and also has a list of dependencies of your projects.
So, first of all go to your project folder and run the following command.
npm install --save express cors
This will take some time and a folder called
node_modules where all the installed dependencies are stored.
Now that our express is installed, let's create a file called
index.js which will be the entry point of our project.
Tip: run command
touch index.js in your terminal to create a new file.