Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/411.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 虽然参数可用,但架构验证失败_Javascript_Node.js_Express_Joi - Fatal编程技术网

Javascript 虽然参数可用,但架构验证失败

Javascript 虽然参数可用,但架构验证失败,javascript,node.js,express,joi,Javascript,Node.js,Express,Joi,我创建了一个RESTAPI,希望在调用控制器逻辑之前验证主体和参数。对于验证,我使用了Joi() 假设我有一个带有一个url参数和一些主体变量的路由。params对象包含此url参数,但Joi仍返回400。详细信息是 “userId”是必需的 我试图创建一个简单的示例来展示我的代码。要重现错误,请创建app.js文件 const express = require('express'); const bodyParser = require('body-parser'); const morga

我创建了一个RESTAPI,希望在调用控制器逻辑之前验证主体和参数。对于验证,我使用了Joi()

假设我有一个带有一个url参数和一些主体变量的路由。
params
对象包含此url参数,但Joi仍返回
400
。详细信息是

“userId”是必需的

我试图创建一个简单的示例来展示我的代码。要重现错误,请创建app.js文件

const express = require('express');
const bodyParser = require('body-parser');
const morgan = require('morgan');
const cors = require('cors');

const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cors());

app.use('/users', require('./routes/users.js'));

app.listen(3000);
由于每个验证都失败,因此只需要一条路径对其进行测试。使用以下内容创建users.js

const express = require('express');
const router = express.Router();

const usersController = require('../controllers/users.js');
const usersControllerPolicy = require('../policies/users.js');

router.get('/:userId', usersControllerPolicy.getUserById, usersController.getUserById);

module.exports = router;
这个users.js控制器文件

exports.getUserById = async (req, res, next) => {
    const { userId } = req.params;
    return res.status(200).json("everything is fine");
};
说到策略,我创建了users.js策略,它将所需的模式添加到中间件中

const joi = require('joi');

const schemaValidation = require('../middleware/schemaValidation.js');

module.exports = {
    getUserById: (req, res, next) => {
        schemaValidation({
            params: {
                userId: joi.string().guid().required()
            },
            body: {}
        }, req, res, next);
    }
}
然后,该模式由myschemaValidation.js验证

const joi = require('joi');

module.exports = (schema, req, res, next) => {
    const { error } = joi.validate(req, schema);

    if (error)
        return res.status(400).json("something went wrong");

    next(); // execute the controller logic
}
如您所见,我传入了整个
req
对象。我这样做是因为有时我必须验证主体和参数。Joi找不到url参数
userId
,因此返回的状态代码为400


如何修复中间件验证以验证
req
对象中的两个对象?

实际上,Joi可以访问
用户ID
,并且可以正确验证它,原因如下:

// replace this
const { error } = joi.validate(req, schema);
// by this
console.log(req.params.userId);
const { error } = joi.validate(req, schema);
console.log(error.toString());
访问
本地主机时的控制台输出:3000/users/10

10
ValidationError: child "params" fails because [child "userId" fails because ["userId" must be a valid GUID]]
在访问参数中包含有效GUID的URL时,如“`”:

ad3756ae-2661-4d8c-aeda-dd51deef5ea9
ValidationError: "_readableState" is not allowed. "readable" is not allowed. "_events" is not allowed. "_eventsCount" is not allowed. "_maxListeners" is not allowed. "socket" is not allowed. "connection" is not allowed. "httpVersionMajor" is not allowed. "httpVersionMinor" is not allowed. "httpVersion" is not allowed. "complete" is not allowed. "headers" is not allowed. "rawHeaders" is not allowed. "trailers" is not allowed. "rawTrailers" is not allowed. "aborted" is not allowed. "upgrade" is not allowed. "url" is not allowed. "method" is not allowed. "statusCode" is not allowed. "statusMessage" is not allowed. "client" is not allowed. "_consuming" is not allowed. "_dumped" is not allowed. "next" is not allowed. "baseUrl" is not allowed. "originalUrl" is not allowed. "_parsedUrl" is not allowed. "query" is not allowed. "res" is not allowed. "route" is not allowed

因此,Joi可以访问它所需的一切,并按预期工作。是的,这很有效:)所以我应该一直采用这种方法?是的,我真的会推荐!我还建议您查看并一起使用,它们还允许进行API验证。最大的好处是验证逻辑可以存储在JSON中,而不是只存储在JS中,这可以提高兼容性。我很高兴它能工作!但请记住这一点——不要在评论中说谢谢,而是投票、接受或奖励赏金;)是的,我得再等六个小时才能赏金:)