Home > Blockchain >  NodeJS App crashes when wrong parameters are passed to the API
NodeJS App crashes when wrong parameters are passed to the API

Time:11-21

I have created an CRUD API using typescript NodeJS, Express and MongoDB. What I am trying to achieve is that when using the POST method when I send the correct parameter. API works fine. However whenever I send incorrect parameters to the API the whole NodeJS app crashes, I get an error message in console that the parameters passed to the API are wrong and I will have restart the application again.

When as user sends the incorrect parameters to the API. I don't want the NodeJS app to crash. I want to display the useful error message. Keep the app running. I Don't want to restart the application.

This is the code i use to create New providers.

    public addProviders(req: Request, res: Response, next: NextFunction) {

    var type = req.body.type,
        name = req.body.name;

    let newProvider = new Provider({
        type,
        name
    })

    newProvider.save()
        .then((provider: Object) => {
            if (provider) {
                let statusCode = res.statusCode;
                res.json({
                    statusCode,
                    provider
                })
            }
        })
}

Below is the code that i have tried so far.

        try {
    newProvider.save()
        .then((provider: Object) => {
            if (provider) {
                let statusCode = res.statusCode;
                res.json({
                    statusCode,
                    provider
                })
            }
        })
    }
    catch (e) {
        res.json("enter valid parameters")
    }

I am new to NodeJS. Thanks in advance.

CodePudding user response:

You need to add input validation middleware to check inputs before adding to Database.

#1 You can check it manually, like:

var { type, name } = req.body;

if (typeof type !== 'string') {
    res.status(400).send("type input is not valid");

} else if (typeof name !== 'string') {
    res.status(400).send("name input is not valid");

} else {
    let newProvider = new Provider({
        type,
        name
    })
    // ...rest of the code
}

#2 Or you can use a package like express-validator.

  • Related