We will create a small REST Api with express

Code on github https://github.com/kendarorg/Angular101

Simple handler

Simply add the following after the express(). This will answer with pong whenever we touch the http://localhost:4201/api/ping address. Remember that you should restart the server!! "Send" means that the content will be sent back as raw

...
var app = express();

app.get("/api/ping", (req, res, next) => {
    res.send("pong");
});
...

A crud service for an address!

List the objects

We need a variable to store all the data and a get function to retrieve those data! We tell express that this call is available for all sites, adding the cors() paramater

var addresses = [];

app.get("/api/address", cors(),(req, res, next) => {
    res.json(addresses);
});

This of course will return an empty json array! "[]"

Add an object

First we have to add support for json

app.use(express.json())

First i try to understand what is sent (and restart the server!!) This will log the body and return a 200. Notice that the response.end() is needed to complete the request!

app.post("/api/address",cors(), (req, res, next) => {
    console.log(req.body);
    res.status(200).end();
});

Then with curl (is in the sources of the demo002srv project, curl.exe if you are on windows)

curl -d "{\"key\":\"value\"}" -H "Content-Type:application/json" -X POST http://localhost:4201/api/address

Then you will see on the log

{ key: 'value' }

Let's suppose that the structure is the following :

  name: string;
  id: number;
  address: string;
  email: string;

Then. When an address with the same id had been found, update it. Meanwhile calculate the greatest id to use when there will be an insert!

app.post("/api/address",cors(), (req, res, next) => {
    var newAddress= req.body;
    var maxId=0;
    for(var i=0;i< addresses.length; i++){
        if(addresses[i].id==newAddress.id){
            addresses[i]=newAddress;
            res.status(200).end();
            return;
        }
        maxId = Math.max(maxId,addresses[i].id);
    }
    newAddress.id=maxId+1;
    addresses.push(newAddress);
    res.status(200).end();
});

And we can now add an item

curl -d "{\"name\":\"A\",\"address\":\"A road\",\"email\":\"a@b.com\"}" -H "Content-Type:application/json" -X POST http://localhost:4201/api/address

And show it!

curl http://localhost:4201/api/address

Get a single object

We should add a parameter then the following will add the "id" field inside the request parameters. We seek the item and then return the json

app.get("/api/address/:id", (req, res, next) => {
    var id = parseInt(req.params.id);
    for(var i=0;i< addresses.length; i++){
        if(addresses[i].id==id){
            res.json(addresses[i]);
            return;
        }
    }
    res.status(404).end();
});

Now adding items with curl and getting them with the following will return the correct data

curl http://localhost:4201/api/address/1

Delete an item

Will be similar to the get

app.delete("/api/address/:id",cors(), (req, res, next) => {
    var id = parseInt(req.params.id);
    for(var i=0;i< addresses.length; i++){
        if(addresses[i].id==id){
            list.splice(i, 1)
            res.status(200).end();
            return;
        }
    }
    res.status(200).end();
});

That can then be called like

curl http://localhost:4201/api/address/2 -X DELETE

Last modified on: February 17, 2020