带有module.exports和prototype的Node.js / Express

时间:2016-08-03 12:22:34

标签: javascript node.js express

当我尝试使用module.exports导出对象后从Object原型访问函数时,我得到:

  

TypeError:无法读取未定义

的属性'auth'

看起来A.prototype.auth没有与module.exports一起传递,但为什么?

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;

1 个答案:

答案 0 :(得分:0)

您需要创建一个新的apiCall.js实例,更改

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

使用

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