【问题标题】:Unable to pass an object to exported javascript module on nodejs / expressjs无法将对象传递给 nodejs / expressjs 上的导出 javascript 模块
【发布时间】:2020-10-05 15:53:51
【问题描述】:

我无法将对象传递给从另一个模块导出的函数。故事是这样的。

我正在从模块 TagService.js

导出一个函数

文件:TagService.js

addTag = ({tag}) => {
  //some activity
}

module.exports = { addTag, //other functions}

从模块ServiceHandler.js

调用函数

文件:ServiceHandler.js

const Controller = require('./Controller');
const service = require('../services/TagService');
const addTag = async (request, response) => {
  await Controller.handleRequest(request, response, service.addTag);
};

以下是 Controller.js

中控制器的结构

文件:Controller.js

static async handleRequest(request, response, serviceOperation) {
  //some activity    
  const serviceResponse = await serviceOperation(this.collectRequestParams(request));
  //some more activity...
}

static collectRequestParams(request) {
  //some activity
  return requestParams;
}

现在,在 Controller 中,requestParams 已成功返回。但是当调用进入 TagService 的 addTag 函数时,对象 tag 没有被传递!

多一点背景。这是从 openapi-generator 为 nodejs-express-server 存根生成的代码。

这是标签服务的 openapi.yaml 模板。

/samyojya-tag:
    post:
      operationId: addTag
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/Tag'
      responses:
        "201":
          content:
...
schemas:
  Tag:
      example:
        name: name
        id: 1
        type: type
      properties:
        id:
          type: string
        name:
          type: string
        category:
          type: string
      type: object
      xml:
        name: Tag

使用 node 12.16.2express 4.16.1

【问题讨论】:

  • 这意味着在TagService.js 中你不能在你的函数addTag 中访问对象?
  • 是的。那是正确的。 @Ifaruki

标签: javascript node.js express scope openapi-generator


【解决方案1】:

我猜问题是你用({...})解构了对象

在您的情况下,您只能从您传递的对象访问属性tag,如果您传递的对象没有名为tag 的属性,则它是未定义的。

您应该将此 ({tag}) 更改为此 (tag) 以完全访问您传递的对象

var obj = {
   test: "i work",
   tag: "i work too"
}

function test({tag}){
   console.log(tag);
}

function test2(tag){
   console.log(tag);
}

test(obj)
test2(obj);

【讨论】:

    猜你喜欢
    • 2016-05-09
    • 1970-01-01
    • 2016-10-15
    • 2012-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-22
    相关资源
    最近更新 更多