简体   繁体   English

当错误的参数传递给 API 时,NodeJS 应用程序崩溃

[英]NodeJS App crashes when wrong parameters are passed to the API

I have created an CRUD API using typescript NodeJS, Express and MongoDB.我使用 typescript NodeJS、Express 和 MongoDB 创建了一个 CRUD API。 What I am trying to achieve is that when using the POST method when I send the correct parameter.我想要实现的是,当我发送正确的参数时使用 POST 方法。 API works fine. API 工作正常。 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.但是,每当我向 API 发送不正确的参数时,整个 NodeJS 应用程序都会崩溃,我会在控制台中收到一条错误消息,提示传递给 API 的参数错误,我将再次重新启动应用程序。

When as user sends the incorrect parameters to the API.当用户向 API 发送不正确的参数时。 I don't want the NodeJS app to crash.我不希望 NodeJS 应用程序崩溃。 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.我是 NodeJS 的新手。 Thanks in advance.提前致谢。

You need to add input validation middleware to check inputs before adding to Database.在添加到数据库之前,您需要添加输入验证中间件来检查输入。

#1 You can check it manually, like: #1您可以手动检查它,例如:

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 . #2或者你可以使用 package 像express-validator

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM