首页 > 解决方案 > 由于未定义,控制器功能中的 res 失败

问题描述

我是 Sails 的新手(也是一名初级开发人员),并且一直在研究这Sailsjs in Action本书。鉴于以前使用 TypeScript 的一些经验,我想以这种能力尝试该框架。但是,当我尝试通过我的 API 返回响应状态和信息时遇到了障碍。

每次我尝试res在我的控制器中使用时,我都会收到一个: TypeError: Cannot read property 'ok' of undefined。根据这本书和文档,我的印象是根据文档中的这个示例自动设置:

await User.create({name:'Finn'});

return res.ok();

书中的这个例子:

signup: function(req, res) {
    var options = {**grab request data**};
    User.create(options).exec(function(err, createdUser){
    if(err){
      return res.negotiate(err);
    }
    return res.json(createdUser);
}

所以我觉得我错过了一些非常明显的东西,但我不确定是什么。该项目编译得很好,我已经安装/配置了记录在案的打字稿库。即使在那里匹配该函数也会返回相同的 TypeError 给我。

另一组眼睛将不胜感激。控制器代码如下。

declare const sails: any;

import { boatInterface } from '../../interfaces/boat';

module.exports = {
    friendlyName: 'new-boat',
    description: 'create a new boat model',

    inputs: {
      modelName:{
        required: true,
        type: 'string',
      },
      yearBuilt:{
          required: true,
          type: 'number'
      }
    },


    exits: {

      success: {
        description: 'New boat model was created successfully.'
      },

      invalid: {
        responseType: 'badRequest',
        description: 'The provided boat info was invalid.'
      },

      modelAlreadyCreated: {
        statusCode: 409,
        description: 'The provided boat model has already been 
        created.',
      },

    },

    fn: async function (req: any, res: any){  
        console.log('building boat');

        let boatRequest: boatInterface = {
            modelName: req.modelName.toLowerCase(),
            yearBuilt: req.yearBuilt
        }

        //confirming data has been formatted correctly
        console.log(boatRequest);

        let newBoat = await sails.models.boat.create(boatRequest)
        .intercept('E_UNIQUE', 'modelAlreadyCreated')
        .fetch();

        //confirming new boat exists
        console.log(newBoat);
        console.log("request successful");

        //res remains undefined and throws an error on attempted return
        console.log(res);
        return res.ok();

      }


};

这是包含一些控制台日志的错误。提前致谢!

building boat
{ modelName: 'kraken', yearBuilt: 1337 } <-- Request formats correctly
{ createdAt: 1566173040652,
  updatedAt: 1566173040652,
  id: 6,
  modelName: 'kraken',
  yearBuilt: 1337 } <-- new db entry is returned via fetch()
request successful
undefined <-- attempt to log the res returns undefined
(node:3738) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'ok' of undefined
    at Object.<anonymous> (/Users/pitterpatter/Repos/learn/sails-learn/freeform/api/controllers/boat/new-boat.ts:67:20)

标签: javascripttypescriptsails.js

解决方案


看起来您正在使用actions2

您的处理程序函数将获得 2 个参数 -inputs正如exits您在上面的对象中定义的那样。

fn: async function (inputs: any, exits: any) { 

inputs将是一个对象,其中包含您在inputs操作部分中定义的用户给出的参数(表单数据/查询参数/路由参数)。在这种情况下,它会包含一个modelNameand yearBuilt,类似于 { modelName: 'lemon', yearBuilt: 2012.3 }

exits将包含一些默认方法 - exits.success()and exits.error(),以及您定义的invalidand 。modelAlreadyCreated

TLDR 试试这个

fn: async function (inputs: any, exits: any) {  
    let boatRequest: boatInterface = {
        modelName: inputs.modelName.toLowerCase(),
        yearBuilt: inputs.yearBuilt
    }

    let newBoat = await sails.models.boat.create(boatRequest)
        .intercept('E_UNIQUE', 'modelAlreadyCreated')
        .fetch();

    return exits.success(newBoat);
}

可以使用or直接访问您正在寻找的“原始快速响应对象” ,但建议您使用适当的“退出”。this.res.ok(...)this.req.something


推荐阅读