Put Request
Put Request, in this article i will step through the sample code on how to use a put request
This Article is an extension from this 2 article (1) (2)
Read the First and Second Article before you proceed to this article.
The Objective of this Program is to replace the existing content inside the “ingredients ” Array by using the “Put ” Request.
var express =require('express'); var app =express(); var bodyParser = require('body-parser'); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({extended: false})); var ingredients=[ { "id":"12345", "text" : "user" }, { "id":"45678", "text" : "user2" }, { "id":"8888", "text" : "user3" } ]; app.get('/ingredients',function(request,response){ response.send(ingredients); }); app.post('/ingredients',function(request,response){ var ingredient = request.body; if(!ingredient || ingredient.text === ""){ response.status(500).send({error:"Your Ingredient must have a String"}); }else{ ingredients.push(ingredient); response.status(200).send(ingredients); } }); app.put('/ingredients/:ingredientId',function(request,response){ var ingredientId =request.params.ingredientId; var text = request.body.text; if(!text ||text ===""){ response.status(500).send({error:"You need to provide Ingredient Text"}); }else{ var objectFound = false; for(var x=0 ; x < ingredients.length;x++){ var ing = ingredients[x]; if(ing.id ===request.params.ingredientId){ ingredients[x].text = text; objectFound = true; break; } } if(!objectFound){ response.status(500).send({error:"Ingredient id not found"}); }else{ respond.send(ingredients); } } }); app.listen(3000,function(){ console.log("My First API Running on port 3000"); });
Before Updating
After Updating
After Updating the “User ” text change to “Brian888”