Home > other >  delete request is not working on postman :
delete request is not working on postman :

Time:08-16

const express = require("express")
const app = express()
app.use(express.json())

const usersList = [{id :1,name:"naser",age:26},{id :2,name:"mosa",age:46}];


app.post('/users',(req,res)=>{
    const newUser = req.body;
    usersList.push(newUser);
    res.status(200).json(usersList)
})

app.delete(`/users/:userId`,(req,res)=>{
    const id = req.params.userId    ;
    usersList.filter(user => {
        user.id !== id
        
    })
    res.status(200).json(usersList)
})

app.listen('3500',()=>
console.log("our server is running")
)

the delete request returns the same array without deleting when i hit "http://localhost:3500/users/2"

whats wrong ?

CodePudding user response:

filter won't change the original array. You need to get the new array and return it.

app.delete(`/users/:userId`,(req,res)=>{
    const id = req.params.userId    ;
    const newUsersList = usersList.filter(user => user.id !== id)
    res.status(200).json(newUsersList)
})

And if you want to change the real usersList, just assign the return value to it instead of assigning it to a new variable named newUsersList

usersList = usersList.filter(user => user.id !== id)

EDIT

you can use below code to remove user from usersList

app.delete(`/users/:userId`,(req,res)=>{
    const id = req.params.userId;
    usersList = usersList.filter(user => user.id !== id)
    res.status(200).json(usersList)
})

UPDATE

based on the comments. the type of id is string. for make filter to works as you expected you have 2 options:

First

you can check the equality with !=

usersList = usersList.filter(user => user.id != id)

Second

you can place in front of req.params.userId or use Number or parseInt functions.

const id =  req.params.userId;

// or
const id = Number(req.params.userId);

// or 
const id = parseInt(req.params.userId);
  • Related