控制器函数中的 res 由于未定义而失败

res in controller function fails due to being undefined

我是 Sails 的新手(并且是初级开发人员)并且一直在阅读 Sailsjs in Action 这本书。鉴于以前使用 TypeScript 的一些经验,我想以这种身份试验该框架。但是,当我尝试通过 API.

return 响应状态和信息时遇到了障碍

每次我尝试在我的控制器中使用 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);
}

所以我觉得我遗漏了一些非常明显的东西,但我不确定是什么。该项目编译得很好,我得到了 documented typescript libraries installed/configured。即使在那里匹配该函数 return 对我来说也是相同的 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)

您似乎在使用 actions2

您的处理函数将获得 2 个参数 - inputsexits,如您在其上方的对象中定义的那样。

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

inputs 将是一个对象,其中包含您在操作的 inputs 部分定义的用户提供的参数(形式 data/query parameters/route 参数). 在这种情况下,它将包含 modelNameyearBuilt,类似 { modelName: 'lemon', yearBuilt: 2012.3 }

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

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);
}

可以使用this.res.ok(...)或[]访问您正在寻找的"raw express response object" =25=],但建议您改用适当的 "exit"。