Express framework learning to write simple API

Time:2020-7-8

I’ve seen the API for so long, but I haven’t studied it carefully. It’s time to have a look.

Initialization environment

npm init -y
npm i -S express

Write an API document

Express framework learning to write simple API

Create a JSON file to store the data

{
  "user1" : {
     "name" : "mahesh",
     "password" : "password1",
     "profession" : "teacher",
     "id": 1
  },
  "user2" : {
     "name" : "suresh",
     "password" : "password2",
     "profession" : "librarian",
     "id": 2
  },
  "user3" : {
     "name" : "ramesh",
     "password" : "password3",
     "profession" : "clerk",
     "id": 3
  }
}

Express framework learning to write simple API

Write a server to listen to the port

Express framework learning to write simple API

Var express = require ('express'); ` please enter the code`
var app = express();
var fs = require("fs");

var server = app.listen(8081, function () {
  var host = server.address().address
  var port = server.address().port
  console.log (application instance, access address: http: //% s: s ", host, port)

})

Write address request interface

For example, write two. One displays all user information, and the other adds a new piece of data

//Display all user information
app.get('/listUsers', function (req, res) {
   fs.readFile( __dirname + "/" + "users.json", 'utf8', function (err, data) {
       console.log( data );
       res.end( data );
   });
})
//Define a new piece of data for insertion
let user = {
  "user4":{
    "name": "mohit",
    "password" : "password4",
    "id":4
  }
}
//Insert data interface information
app.get('/addUser',function(req,res){
  //Read data
  fs.readFile(__dirname+"/users.json",function(err,data){
    data = JSON.parse(data);
    data["user4"] = user["user4"];
    console.log(data);
    res.end(JSON.stringify(data));
  })
})