I am creating an express app that allows a user to add web projects into a list using get, post, put and delete. I have been able to write the logic for the get, delete and post requests and they work fine. I am not sure on how to allow for the user to edit the information that is in the array.
const express = require('express');
const app = express();
const port = 8080;
app.use(express.json());
let webProjects = [
{ID: 1, TITLE: "React Game", DESCRIPTION: "Tic tac toe game created using Create React App", URL: "http://heroku/myapp/game/"},
{ID: 2, TITLE: "Online Store", DESCRIPTION: "Online store created with HTML, CSS and Javascript.", URL: "http://git.com/myrepos/shop/index"}
]
app.get('/api', (req, res) => {
res.send(webProjects)
})
//the :id allows to capture a dynamic value in url
app.post('/api/:id/:title/:description/:url', (req, res) => {
const { id } = req.params;
const { title } = req.params;
const { description } = req.params;
const { url } = req.params;
const bob = {ID:id, TITLE:title, DESCRIPTION:description, URL:url}
webProjects.push(bob)
res.send(webProjects)
});
app.delete('/api/:id', (req, res) => {
const { id } = Number(req.params);
const index = webProjects.indexOf(id)
const deleteObj = webProjects.splice(index, 1)
res.send(`The item was successfully deleted`)
})
app.put('/api/', (res, req) => {
})
app.listen(port , () => {
console.log('Its working')
})
4
Answers
I’d claim it’s at least best practice to receive data for
PUT
andPOST
via the request body. Only put theid
of the item you want to update in the url as a parameter.You could do something similar to this:
Firstly bad practice is to use req.params for adding data in the post API instead you can use body for gatting the data that you want to push in the array:
Now about the updating first you need to find the element that you want to update. Id needs to be extracted from the params and use PUT method.
Here is the working example:
You should also consider to update your delete route.
Otherwise you wolud always delete the last Project in the array.