简体   繁体   English

带有module.exports和原型的Node.js / Express

[英]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: 当我使用module.exports导出对象后尝试从Object原型访问函数时,我得到:

TypeError: Cannot read property 'auth' of undefined TypeError:无法读取未定义的属性“ auth”

It looks like the A.prototype.auth is not passed with module.exports, but why? 看起来A.prototype.auth没有与module.exports一起传递,但是为什么呢?

Server.js 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 /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;

You need to create a new instance of apiCall.js, Change 您需要创建一个新的apiCall.js实例,将其更改

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

With

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM