【问题标题】:Why when I try to send data to my Controller it returns me an error?为什么当我尝试向我的控制器发送数据时它返回一个错误?
【发布时间】:2018-12-31 06:58:43
【问题描述】:

我有一个模型 (User.js) 和一个控制器 (UserController.js),我在 blueprints.js 中设置了“ations: true”,我在 UserController 中还有一个名为“datos”的函数

使用 Postman 我发送一个 json 对象:

{
    "nombre": "Alexkin",
    "apellido": "Skywalker",
    "correo": "alexkin2@mail.com",
    "password": "123"
}

到这个网址:localhost:1337/user/datos

这是我的代码:

用户.js

module.exports = {

    attributes: {
        nombre:
        {
            type: 'string',
            required: true
        },
        apellido:
        {
            type: 'string',
            required: true
        },
        correo:
        {
            type: 'string',
            required: true,
            unique: true,
            isEmail: true
        },
        password:
        {
            type: 'string'
        },
    },
};

用户控制器.js

module.exports = {
    datos: function (req,res)
    {
        usuario = req.allParams();
        User.findOrCreate(usuario)
        .exec(async(err, user, wasCreated)=> {
            if (err) { return res.serverError(err); }

            if(wasCreated) {
                sails.log('Created a new user: ' + user.nombre);
            }
            else {
                sails.log('Found existing user: ' + user.nombre);
            }
       });
    }
};

我希望在我的数据库中创建一个不存在的用户,但最后我收到一条带有此错误的消息:

错误:发送 500(“服务器错误”)响应:UsageError: Invalid 新记录的初始数据。详细信息:所需的缺失值 属性nombre。期望一个字符串,但得到:未定义 [?] 请参阅https://sailsjs.com/support 寻求帮助...

【问题讨论】:

  • User 模块的 findOrCreate 方法内部发生了什么?
  • migrateconfig/model.js 中的值是多少?
  • 我在 models.js 中有“安全”
  • 您能否在User.findOrCreate() 之前先console.log(usuario) 向我们展示价值?
  • 我已经这样做了,它显示了 json 对象:{ nombre: 'Alexkin', apellido: 'Skywalker', correo: 'alexkin4@mail.com', password: '123' } 错误:发送 500(“服务器错误”)响应:UsageError:新记录的初始数据无效。详细信息:必需属性 nombre 缺少值。期望一个字符串,但得到:undefined

标签: node.js sails.js


【解决方案1】:

将 postman 中的 content-type 设置为 application/json。然后将 json 粘贴到“原始”选项卡中。

【讨论】:

    【解决方案2】:

    我找到了答案,问题是在版本 1.0 中,您必须发送两个对象 [Model.findOrCreate (查找,数据)]...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-04-14
      • 2022-08-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-30
      • 2021-03-11
      相关资源
      最近更新 更多