我创建了一个简单的 API,其中包含所有动词 GET、PUT、POST、DELETE,但在此,我想验证 POST 数据。
我尝试过 Joi Libary,但没有找到正确的方法。
CodeSnippet of POST Method
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");
}
});
Snapshot of Controller
最佳答案
您可以使用这个:validator由谷歌创建,他们使用它来验证查询参数,但您可以使用它来验证有效负载。 它简单且可扩展
并像这样使用它:
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
}
关于node.js - 如何在 Node js 中验证 API 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49605287/