使用 Joi、nodejs 验证 header 参数?
Validate a header parameter with Joi, nodejs?
我想检查 HTTP 请求的 header 的一个参数(在本例中为 docsLimit)。所以我这样做了:
const {
celebrate,
Joi,
} = require('celebrate');
const joiObjectId = require('joi-objectid');
Joi.objectId = joiObjectId(Joi);
const limit = celebrate({
headers: Joi.object().keys({
docsLimit: Joi.number()
.required()
.default(10),
}).options({ allowUnknown: true })
});
module.exports = limit;
在app.js中:
app.get(path, limit, getDocuments);
我不得不说我是 nodejs 的新手,尤其是 Joi,但这对我来说似乎很有意义。这是错误的,因为如果我在 headers 中发送一个字符串,它无论如何都会接受它,即使我将它精确为一个数字。如果我删除 .options({ allowUnknown: true }) 然后它永远不会通过,即使有一个数字。它说“UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client” 和 returns a json 表示“不允许限制” .使用 Joi 检查 headers 中的参数的方法是什么?
非常感谢!
问题是 header 始终是一个字符串,所以我不应该执行 Joi.number()。我应该使用 Joi.string() ,然后我用正则表达式检查是否是一个数字。最后我在使用它之前将它转换为数字!
我想检查 HTTP 请求的 header 的一个参数(在本例中为 docsLimit)。所以我这样做了:
const {
celebrate,
Joi,
} = require('celebrate');
const joiObjectId = require('joi-objectid');
Joi.objectId = joiObjectId(Joi);
const limit = celebrate({
headers: Joi.object().keys({
docsLimit: Joi.number()
.required()
.default(10),
}).options({ allowUnknown: true })
});
module.exports = limit;
在app.js中:
app.get(path, limit, getDocuments);
我不得不说我是 nodejs 的新手,尤其是 Joi,但这对我来说似乎很有意义。这是错误的,因为如果我在 headers 中发送一个字符串,它无论如何都会接受它,即使我将它精确为一个数字。如果我删除 .options({ allowUnknown: true }) 然后它永远不会通过,即使有一个数字。它说“UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client” 和 returns a json 表示“不允许限制” .使用 Joi 检查 headers 中的参数的方法是什么?
非常感谢!
问题是 header 始终是一个字符串,所以我不应该执行 Joi.number()。我应该使用 Joi.string() ,然后我用正则表达式检查是否是一个数字。最后我在使用它之前将它转换为数字!