【问题标题】:Is there a way I can access the express's Application in a REST API?有没有办法可以在 REST API 中访问 express 的应用程序?
【发布时间】:2015-09-02 10:29:43
【问题描述】:

看Massive的documentation,节省数据库连接执行时间的方法是将连接对象保存一次到Express的应用程序设置中。我的问题是,如何在 REST API 模块化时访问 Express 的 app 变量?问题示例:

app.ts:

import express = require('express');
import greeter = require('./api/greeter');

var app = express();

app.get('/api/greeter', greeter.get);

greeter.ts:

import express = require("express");

function get(req: express.Request, res: express.Response, next: Function): any   
{
    // The this object seems not the Express's app object.
    // console.log(this)        

    // How to access Express's app variable here?        
    // var db = app.get('db');

    db.item.findOne({item_id : 1}, (err, item) => {
        res.json(item);
    }); 

}

我在get RequestHandler中检查了这个对象,这个对象似乎不是Express的app对象。也检查了req和res参数,好像Express的app对象也不存在。


谢谢@robertklep

Express TypeScript 定义未更新。为了 TypeScript 用户的利益,只需通过 indexer 访问应用程序。这有效:

import express = require("express");

export function get(req: express.Request, res: express.Response, next: Function): any {

    var app : express.Application = req["app"];

    var db = app.get('db');

【问题讨论】:

    标签: node.js rest express typescript massive


    【解决方案1】:

    req.appres.app 均可使用。

    【讨论】:

      猜你喜欢
      • 2016-05-14
      • 1970-01-01
      • 1970-01-01
      • 2017-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-09
      相关资源
      最近更新 更多