Manihtraa
Manihtraa

Reputation: 978

how to call other js function in server.js file?

I am using the express js. i want to access the other file js function in server.js. please any one help me.

server.js

 var express = require('express'),
 path = require('path'),
 cors = require('cors'),
 bodyParser = require('body-parser'),
 routes = require('#######'), //web routes
 connection = require("######"); //mongodb connection
 authChecker = require("./###/authChecker");

 var app = express();
 app.use(bodyParser.json());
 app.use(express.static(path.join(__dirname, 'app')));
 app.use(express.static('node_modules'));
 app.use(cors());
 app.use(authChecker);
 app.use('/', routes);

My authChecker js file is

authChecker.js

module.exports = {
function(req, res, next) {
    console.log("authondication checker process");
    if (req.session.auth || req.path === '/auth') {
        next();
    } else {
        res.redirect("/auth");
    }
}
}

when app.use(authChecker) this line execute this error is shown while sever startup.

 E:\MEAN_STACK\MySampAps\Crud_samp\node_modules\express\lib\application.js:210
throw new TypeError('app.use() requires middleware functions');
^

TypeError: app.use() requires middleware functions
at Function.use (E:\MEAN_STACK\MySampAps\Crud_samp\node_modules\express\lib\application.js:210:11)
at Object.<anonymous> (E:\MEAN_STACK\MySampAps\Crud_samp\server.js:39:5)
at Module._compile (module.js:569:30)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:503:32)  

Upvotes: 0

Views: 304

Answers (2)

Himanshu sharma
Himanshu sharma

Reputation: 7881

check this out server.js

var express = require('express'),
 path = require('path'),
 cors = require('cors'),
 bodyParser = require('body-parser'),
 routes = require('#######'), //web routes
 connection = require("######"); //mongodb connection
 authChecker = require("./###/authChecker").auth;

 var app = express();
 app.use(bodyParser.json());
 app.use(express.static(path.join(__dirname, 'app')));
 app.use(express.static('node_modules'));
 app.use(cors());
 app.use(authChecker);
 app.use('/', routes);

My authChecker js file is

authChecker.js

module.exports = {
auth:function(req, res, next) {
    console.log("authondication checker process");
    if (req.session.auth || req.path === '/auth') {
        next();
    } else {
        res.redirect("/auth");
    }
}
}

Upvotes: 1

SNahar
SNahar

Reputation: 134

You can modify the authChecker.js to be like this :

module.exports = function(req, res, next) {
console.log("authondication checker process");
if (req.session.auth || req.path === '/auth') {
    next();
} else {
    res.redirect("/auth");
}}

then you can call that function in server.js by this : app.use(authChecker)

Hope this helps

Upvotes: 2

Related Questions