【问题标题】:app.use() requires middleware functionsapp.use() 需要中间件函数
【发布时间】:2015-12-08 08:49:07
【问题描述】:

我正在为我的应用程序使用 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() 需要中间件函数

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

【问题讨论】:

  • undefinedmyProject.callService() 返回的内容)不是有效的中间件。
  • 那么我怎样才能使它成为一个有效的中间件,我已经尝试过exports.callService= function () { return function (req, res, next) { next(); } } 但不工作
  • 通过传递函数而不是执行它。
  • 嘿,凯文,这个网站是干什么用的,我想问一下哪个有混淆的问题。因此,与其给出答案,为什么还要继续将其标记为否定。我不认为这是一个无关紧要的问题
  • 我也没有投反对票,但您的问题并未表明您已阅读或研究过任何中间件的简单示例,因为任何中间件必须调用 next() 或完成请求本身所以即使你正确地传递了中间件函数引用,你所拥有的仍然行不通。

标签: javascript node.js


【解决方案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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-10-17
    • 1970-01-01
    • 1970-01-01
    • 2017-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多