For loop in route.patch does not work. || Exprees.js

Viewed 85

Below is the piece of code for my route.patch function that I defined for /:productId

route.patch('/:productId',(req,res,next)=>{
    
    const id = req.params.productId;
    const updateOps = {};
    console.log(req.body);
    for (const ops of req.body) {
        updateOps[ops.propName] = ops.value;
        console.log(updateOps);
    }
    
    res.status(200).json({Message: 'Hi'});
});

console.log(req.body) before the for loop is working but the console.log(updateOps) inside for loop is not working. And the even the res.status(200).json({Message: 'Hi'}); is not working . I am getting a route not found error. Basically everything before for loop is working and everything after for loop is not working.

Can you please let me know where am I doing wrong. Is it the way I use for loop inside route.patch is wrong? Any help is highly appreciated.

Thanks

1 Answers

Answering your question regarding the error-handling from the comments. You have the following middlewares:

app.use((req, res, next) => {
    const error = new Error('Not found');
    //console.log(error.status) //console.log(error.message) 
    error.status = 404; //console.log(error.message) 
    next(error);
});

app.use((error, req, res, next) => {
    res.status(error.status || 500);
    res.json({
        error: {
            message: 'Route not found'
        }
    })
});

So for every request an error-object will be created which you assign status 404 and pass it on to the next middleware. There you send the error response and since the status is already set to 404 this status is used.

Actually you should just remove the first middleware where you create the error, as this would be done for every request. Express already handles requests to routes that do not exist and will return a 404 not found response. You can keep the second middleware to handle any other unhandled errors though (you should change the error message though :))

Related