When i try to change my objects in my array it wont work. I want to be able to call it in postman with the a new value attahed to the item i call. please help, it's an assignment for today
const express = require("express");
const {emitWarning} = require("process");
// laver en variabel hvor sætter en execution af express til den
const app = express()
//Nedenunder laver jeg en port med nummer 8080 som vil bruges igennem hele opgaven
const PORT = 8081;
//bruger console.log til at printe beskeden og det gør jeg ved hjælp af en listen method
app.listen(PORT, () => console.log("server lytter på port 8080"))
//Opgave B
//jeg laver min array hvor jeg putter kategorierne ind samt antallet til hver kategori
var besatning = [
{id:0, kategori: 'Køer', antal: 50 },
{id:1, kategori: 'Hunde', antal: 1 },
{id:2, kategori: 'Grise', antal: 100 },
{id: 3, kategori: 'Får', antal: 20 },
];
app.put('/ny_besætning/:kategori/:antal', (req, res)=> {
if (req.params.kategori in besatning){
besatning[req.params.kategori] = req.params.antal;
res.json(besatning);
} else{
res.sendStatus(404)
}
});
It looks like your trying to access an array of objects as if it was an array of strings.
Try and change this:
if (req.params.kategori in besatning){
besatning[req.params.kategori] = req.params.antal;
res.json(besatning);
} else{
res.sendStatus(404)
}
To this
const result = besatning.find(item => item.kategori === req.params.kategori);
if (result) {
res.json(result);
} else {
res.sendStatus(404);
}
This will return the matching item. And should be called with a GET request.
PUT requests are to update an item, generally by an id. Your url be something like "/ny_besætning/:id" and then use the find filter to get the item based on the id. When updating the item, it should be done via a the payload (i.e. in postman its the body tag) in the format of a full object i.e: {id:0, kategori: 'updated', antal: 9999 }