【问题标题】:TypeError: expected string but received array postmanTypeError:预期的字符串,但收到数组邮递员
【发布时间】:2019-06-29 21:37:35
【问题描述】:

我试图发送具有多个同名字段的表单数据,但我返回“TypeError:预期的字符串但收到的数组”。

我认为问题出在邮递员身上,我希望有多个参与者字段,这些字段将被添加到应该添加到数组中。

final results of array

// this is from models/Battle

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

// Create Schema
const BattleSchema = new Schema({
    user: {
        type: Schema.Types.ObjectId,
        ref: 'users'
    },
    date: {
        type: Date, 
        default: Date.now
    },
    category: {
        type: Number, 
        required: true // this will come from the selected category 
    },
    winner: {
        type: Number, 
        default: 0
    },
    status: {
        type: Number, 
        default: 0 // 0 means the battle is closed, 1 means the battle is open for votes, the status will stay 0 until all participants dropped
    },
    participants: [
        {
          participant: {
            type: Schema.Types.ObjectId,
            required: true
          }
        }
    ]
    
 

});

module.exports = Battle = mongoose.model('battles', BattleSchema);

//this is from routes/api/battles

// @route   POST api/battles
// @desc    Create battle
// @access  Private
router.post(
    '/create-battle',
    passport.authenticate('jwt', { session: false }),
    (req, res) => {
      const { errors, isValid } = validateBattleInput(req.body);
  
      // Check Validation
      if (!isValid) {
        // If any errors, send 400 with errors object
        return res.status(400).json(errors);
        console.log(errors);
      }

      const newBattle = new Battle({
         user: req.user.id,
         category: req.body.category,
         participant: req.body.participant
      });      

      //save
      newBattle.save().then(battle => {       

        // const participant = req.body.participant;
        const participant = req.body.participant;


        // add participants to array 
        battle.participants.push( participant );
        console.log(typeof req.body.participant);

        // get the inserted id  
        const battleId = battle._id;
        res.json(battle);      

      
      });
    }
);

// this is battle validation 
const Validator = require('validator');
const isEmpty = require('./is-empty');
var bodyParser = require('body-parser');

module.exports = function validateBattleInput(data) {
  let errors = {};

  data.category = !isEmpty(data.category) ? data.category : '';
  data.participant = !isEmpty(data.participant) ? data.participant : '';

  if (Validator.isEmpty(data.category)) {
    errors.category = 'Category field is required';
  }

  // if (Validator.isEmpty(data.challenger)) {
  //     errors.challenger = 'Challenger field is required';
  // }

  if (Validator.isEmpty(data.participant)) {
    errors.participant = 'Participant field is required';
  }

  return {
    errors,
    isValid: isEmpty(errors)
  };
};

【问题讨论】:

  • TypeError: expected string but received array 已被validator lib 抛出,您可以按照错误堆栈跟踪然后再次检查。 validation/battle.js line 18。我明白了,participants(在模型中)!= participant(在创建数据中)

标签: node.js express mongoose postman


【解决方案1】:

TypeError:预期的字符串,但收到的数组。 --- 在邮递员和终端窗口中引发错误。我怀疑可能是用户架构定义不匹配

请检查您的用户模型用户架构,例如 姓名: { 类型:字符串, 要求:真 } 它收到了超出预期的东西。

【讨论】:

    【解决方案2】:

    尝试在“body”选项卡中选择“raw”,然后在右侧选择“JSON (application/json)”而不是“text”。

    我假设您的 API 端点使用 JSON 而不是 url 编码的表单数据,只是因为您正在使用 express 和 mongoose 运行 API。但如果不是这种情况,你应该澄清这个问题。

    编写一个正确的 JSON 正文,我的意思是,对键使用双引号,如下所示:

    {"model": { "property": "value",  "property2": 1}}
    

    并尝试使用包装对象{"model": <YOUR BODY HERE>} 或不使用,看看什么对你有用,因为包装对象是典型的,但有时人们不使用它们。 (在您的代码中看到这一点:req.body.participant 让我觉得您可能没有)。

    (PS:与问题无关,但个人更喜欢ARC或Insomnia,因为他们的界面更干净)

    【讨论】:

    • 当我进入 UI 并且可以处理实际表单时,我认为我不会遇到这个问题,因为我可以在 name 属性中传入 property[],那不会不过在这种情况下工作。
    • 你的应用是 MEAN 式的吗?
    • 是的,除了 mern 使用 react 而不是 angular,我需要将多个参与者添加到参与者数组中。该模型看起来像参与者:[ {参与者:{ type:String,required:true }}]我尝试将type更改为array,但它不起作用,它实际上曾经使用type:String
    • 我想我明白了,因为参与者被认为是一个数组,我可以遍历参与者并添加到数组中,如果这是一个 php 应用程序,我会这样做。
    • 哦,BAM,通过参与者数组的循环工作const participants = req.body.participant; participants.map(battlers => { battle.participants.unshift({participant: battlers}); });
    【解决方案3】:

    如果您希望在参与者数组中发送数据,则所有字段都应该是参与者而不是参与者

    尝试通过原始数据发送数据,然后选择应用程序/数据以获得更好的格式

    【讨论】:

      【解决方案4】:

      在 postman 中进行测试时 - 刚刚发现 Key 值必须与您的验证函数定义的变量匹配。最好在整个开发过程中保持一致。

      【讨论】:

      • 请不要为同一件事发布两个答案,尝试编辑您的另一个答案!
      猜你喜欢
      • 2020-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-30
      • 2021-09-19
      • 2016-12-16
      • 1970-01-01
      相关资源
      最近更新 更多