SDeba SDeba - 4 months ago 15
Node.js Question

Node.js / Express with module.exports and prototype

When I am trying to access function from Object prototype after exporting the object with module.exports, I get:


TypeError: Cannot read property 'auth' of undefined


It looks like the A.prototype.auth is not passed with module.exports, but why?

Server.js

'use strict';

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

var AReq = require('./src/apiCall');
var A = AReq("a", "b");

var serverPort = 3000; // Server port
var __apipath = "/api/v1/"; // API path

app.use(bodyParser.json());

// Authentication API route
app.get(__apipath + "auth", function (req, res) {
return A.Auth;
})

// Server listener setup
app.listen(serverPort, function () {
console.log('Server has been started on port ' + serverPort);
});

module.exports = app;


/src/apiCall.js

'use strict';

function A(login, password) {
var options_auth = {
user: login,
password: password
};
}

A.prototype.auth = function () {
return "test";
};

module.exports = A;

Answer

You need to create a new instance of apiCall.js, Change

var AReq = require('./src/apiCall');
var A = AReq("a", "b");

With

var AReq = require('./src/apiCall');
var A = new AReq("a", "b");