You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Express Validator适配自定义嵌套请求体结构问题咨询

Fixing Express Validator for Nested Request Body Data

Hey there! I totally get where you're stuck—your POST request body nests all required fields under the data key, but your current validation rules are checking for fields directly at the top level of req.body instead of inside req.body.data. Let's get this sorted out quickly.

Step 1: Update Validation Rules to Target Nested Fields

Express Validator supports dot notation to access nested properties in the request body. All you need to do is prefix each field name with data. in your check() calls. Also, I noticed a small issue in your original rules: you're using .isEmpty() which validates that a field is empty (the opposite of what you want!). Swap that for .notEmpty() to ensure fields are present and not blank.

Here's your updated validation rules file:

const { check, validationResult } = require('express-validator');

const createPostRules = [
  // Validate nested fields using dot notation
  check('data.local_db_path')
    .notEmpty()
    .withMessage('Post Key is missing'),
  check('data.source_type')
    .notEmpty()
    .withMessage('Post source type missing')
    .isIn(['google', 'imdb'])
    .withMessage('Invalid source type'),
  check('data.source_id')
    .notEmpty()
    .withMessage('Post source key missing'),
  check('data.box_ids')
    .notEmpty()
    .withMessage('Box Information is missing')
    .isArray()
    .withMessage('Box IDs must be an array') // Optional: Add array type validation for extra rigor
];

module.exports = { createPostRules };

Step 2: Keep Your Controller Logic (Almost) the Same

You don't need big changes to your controller—validationResult(req) will automatically pick up errors from nested fields as long as your rules use the correct dot notation. Just make sure you access the nested data from req.body.data when processing the request:

const { validationResult } = require('express-validator');

exports.createPost = (req, res) => {
  // Check for validation errors
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return res.status(400).json({ errors: errors.array() });
  }

  // Access the nested post data safely
  const postData = req.body.data;
  
  // Your existing logic to create the post goes here...
  res.status(201).json({ message: 'Post created successfully', data: postData });
};

Why This Works

Express Validator parses the dot notation in check() to traverse the request body object. So check('data.local_db_path') directly maps to req.body.data.local_db_path, which is exactly where your fields live in the request.

That's it! Your validation should now correctly validate all nested fields in your POST request body.

内容的提问来源于stack exchange,提问作者Rizwan Saleem

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 00:12:43