0
votes

I am using express and node js for my app

my main index.js file is

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());

and my services.js file is

var res = module.exports;

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

but when I am trying to call this callService function from index.js I am getting an error

app.use() requires middleware functions

can you please tell what I am doing wrong here.

1
undefined (which is what myProject.callService() returns) isn't valid middleware.Kevin B
so how can I make it as a valid middleware, I have tried it as exports.callService= function () { return function (req, res, next) { next(); } } but not workingBhushan Goel
By passing the function instead of executing it.Kevin B
hey kevin what is this site for, I think asking questions about which one have confusion. So instead of giving answers why are you keep on marking it negative. and I don't think it is an irrelevent questionBhushan Goel
I didn't downvote either, but your question doesn't show that you've read or studied any of the simple examples of middleware as any middleware must either call next() or finish the request itself so even if you had passed the middleware function reference correctly, what you have still wouldn't work.jfriend00

1 Answers

1
votes

You need to pass a middleware function, not pass the result of calling your endpoint handler.

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);