簡體   English   中英

如何在 Node js 中驗證 API 請求

[英]How to validate API request in Node js

我創建了一個簡單的 API,其中包含所有動詞 GET、PUT、POST、DELETE,但在這里,我想驗證 POST 數據。

我嘗試過 Joi Libary,但沒有找到正確的方法。

POST 方法的代碼片段

    appRouter.route('/')
        .post(function (req, res) 
        {            
            if (req.body.ProductName) 
            {
                conn.connect().then(function () {
                    var transaction = new sql.Transaction(conn);
                    transaction.begin().then(function () {
                        var request = new sql.Request(transaction);
                        request.input("ProductName", sql.VarChar(50), req.body.ProductName)
                        request.input("ProductPrice", sql.Decimal(18, 0), req.body.ProductPrice)
                        request.execute("Usp_InsertProduct").then(function () {
                            transaction.commit().then(function (recordSet) {
                                console.log(recordSet);
                                conn.close();
                                res.status(200).send(req.body);
                            }).catch(function (err) {
                                console.log("Error in Transaction Commit " + err);
                                conn.close();
                                res.status(400).send("Error while inserting data");
                            });
                        }).catch(function (err) {
                            console.log("Error in Transaction Begin " + err);
                            conn.close();
                            res.status(400).send("Error while inserting data");
                        });

                    }).catch(function (err) {
                        console.log(err);
                        conn.close();
                        res.status(400).send("Error while inserting data");
                    });
                })
                    .catch(function (err) {
                        console.log(err);
                        conn.close();
                        res.status(400).send("Error while inserting data");
                    });
            }
            else {
                res.status(400).send("Error while inserting data");
            }
        });

控制器快照

控制器

您可以使用這個:由 google 創建的驗證器,他們使用它來驗證查詢參數,但您可以使用它來驗證有效負載。 它簡單且可擴展

並像這樣使用它:

const v = require('./validator')
// then test your payload like this...
const testPayload = (req, res, next) => {
try {
    const validate = v.object({
        username: v.string, //required field, string
        password: v.string, // required field, string
        age: v.number, // required field, number
        opt: v.optional(v.array(v.string))) // optional field, array of string
    })
    validate(req.body);
    next() // if everything goes well pass it to next middle ware, or handle your payload
}
catch (err) {
   next(err) // handling common error
}

您可以結合使用 Joi 和中間件來驗證所有參數。 例如,如果您想從請求正文中驗證ProductName

const validateParams = function (paramSchema) {
    return async (req, res, next) => {
        const schema = Joi.object().keys(paramSchema);
        try{
            await Joi.validate(paramSchema, schema);
        } catch (err) {
            return res.send(400, {
                status: 400,
                result: err.details[0].message
            });
        }
        next();
    }
};

function routeFunction (req, res, next) {
    // do anything you want to
}
server.post(`${routeURI}/abc`, validateParams({
        ProductName: Joi.string().required(),
    }), routeFunction);

同樣,如果您想驗證響應,您可以創建類似的中間件並使用 Joi 實現相同的目的。

我通常使用express-validator來驗證 API 請求。 它基於validator.js 您可以輕松驗證類型、字段長度,甚至可以構建自己的自定義函數來驗證字段。 而且這個包還可以很容易地向用戶返回哪些字段不正確以及為什么不正確。

API 調用返回的驗證錯誤示例。

[
    {
        "location": "params",
        "param": "is_active",
        "msg": "Missing is_active param."
    },
    {
        "location": "params",
        "param": "is_active",
        "msg": "is_active param must be boolean true or false."
    }
]

您可以使用自己的中間件函數來驗證 api。 此鏈接包含有關使用 express 框架的中間函數的信息: http : //expressjs.com/en/guide/using-middleware.html

您可以將中間件用於 POST 請求的 url 或僅用於 POST 請求。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM