Initiate RESTful API with express.js
Start with creating an empty folder and open the terminal (Mac or Linux). If you used windows, prefer to use “cmder” for windows. Then type CD command-line access to that folder and then run init command.
npm init
It will dialog message asking for more information about this project, and you can skip it with press enter to all questions. At the end of this process, you will get a package.json file, and now we can run “npm install” to get the node_module folder containing our default node package.
npm install
Install Express
Install express.js package, the core package, to make the restful API.
npm install express --save
Install nodemon
the tool helps develop node.js based applications by automatically restarting the node application when file changes in the directory are detected.
npm install --save-dev nodemon
Start to create the first API
Create an index.js file, then import express package with “require()” function stuff to variable with “const”, and then execute that express function to a new variable, give it a name “app”. And made the first route with app variable call the domestic get function. It required two parameters, a string for route suffix name and a callback function that build-in two parameters, req is request information. The res is the response module to send a response to the client’s browser. And the last coding could end with calling the listen to function to start the webserver with port 3001.
const express = require('express')
const app = express()app.get('/', (req, res) => {
res.send('my first route.')
})app.listen('3001', () => {
console.log('started: localhost:3001')
})
Executed with run the nodemon to execute index.js file. and then open the browser and type this URL, HTTP://localhost:3001
nodemon index.js
Good luck ^_^