app.use()需要中间件函数

时间:2015-09-11 17:56:02

标签: javascript node.js

我正在为我的应用程序使用express和node js

我的主要index.js文件是

var express = require("express");
var app = module.exports = express();

var bodyParser = require('body-parser');

var MongoClient = require('mongodb').MongoClient
    , assert = require('assert');

var myProject= require("services");

app.use(myProject.callService());

和我的services.js文件是

var res = module.exports;

res.callService = function () {
    console.log('here ===')
}

但是当我尝试从index.js调用此callService函数时,我收到错误

app.use()需要中间件功能

你能告诉我这里做错了吗?

1 个答案:

答案 0 :(得分:1)

您需要传递中间件函数,而不是传递调用端点处理程序的结果。

services.js

// a middleware function gets the request(`req`), response(`res`)
// and a `next` function to pass control to the next handler
// in the pipeline.
exports.callService = function (req, res, next) {
    console.log('here ===');
    res.status(200).end();
};

index.js

/* setup stuff... */
// notice here we do not call callService, but pass it
// to be called by the express pipeline.
app.use(myProject.callService);