node.js - inversify-restify-utils Controller 中的空上下文和主体

标签 node.js express restify inversifyjs

我尝试开始工作inversify-restify-utils,但遇到了问题。请求上下文和主体变量为空。 我的 Controller :

@Controller('/users')
@injectable()
export class UsersController implements interfaces.Controller {

  @Post('/')
  createUser(req: restify.Request, res: restify.Response, next: restify.Next) {
    console.log(req.body); // undefined
  }
}

我的服务器.ts:

// to get query params in req.query
this.server.use(restify.acceptParser(this.server.acceptable));
// to get passed json in req.body
this.server.use(restify.bodyParser());

this.server.post('/test', (req, res, next) => {
  console.log(req.body); // ok
  next();
});

有什么建议吗?

最佳答案

我错误配置了服务器。我需要在创建应用程序时添加 setConfig():

//create restify application
this.app = new InversifyRestifyServer(container, {
  name: AppConstants.APP_NAME,
  version: nconf.get("server:api_version"),
  log: this.logger
}).setConfig((app) => {
  this.config(app); // configure app
}).build();

配置示例。

public config(app) {
    // configure cors
    app.use(restify.CORS({
      origins: nconf.get("server:origins"),   // defaults to ['*']
      credentials: false,                 // defaults to false
    }));

    // to get query params in req.query
    // this.server.use(restify.queryParser());
    app.use(restify.acceptParser(app.acceptable));
    // to get passed json in req.body
    app.use(restify.bodyParser());

    setupPassport(passport);

    app.post('/test', (req, res, next) => {
      console.log(req.body);
      res.json(new Response(true, 'ok'));
      next();
    });

    // start listening
    app.listen(this.getPort(), this.getHost(), () => {
      log(`${app.name} listening at ${app.url}`);
    });
    // error handler
    app.on('error', (error) => {
      this.onError(error);
    });
    // process exceptions
    app.on('uncaughtException', function (request, response, route, error) {
      console.error(error.stack);
      response.send(error);
    });
    // audit logger
    app.on('after', restify.auditLogger({
      log: this.logger
    }));
  }

关于node.js - inversify-restify-utils Controller 中的空上下文和主体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44132075/

相关文章:

ajax - 将 jQuery JSON 对象发布到 NodeJs Restify

javascript - 如何使用 Cocos2dJS 连接到 Socket.IO 服务器?

javascript - 从 Promise 返回非返回函数导致警告

node.js - RESTify 或 KOA.js 哪个更适合 API 创建

javascript - react 路线与 URL 参数不更新 View

node.js - 使用 Azure cosmos DB 进行表达

javascript - 默认情况下,response.send(来自node.js/restify应用程序)将整数序列化为32位低/高部分?

node.js - 使用phonegap/cordova时,“node”不被识别为内部或外部命令、可操作程序或批处理文件

javascript - Quickblox 字符串化通知

ruby-on-rails - 在 PPC linux (lubuntu 12.04) 上安装 Rails