Javascript module.export函数指针的结构

时间:2017-02-17 21:30:25

标签: javascript node.js express

运行节点应用时,我得到以下信息:

Error: Route.post() requires callback functions but got a [object Undefined]

我的app.js文件中有以下内容:

const express = require('express')
const path = require('path')
const port = process.env.PORT || 3000
const app = express()

// imports
var bodyParser = require('body-parser');
var api = require('./api/controllers/apiController.js');

// serve static assets normally
app.use(express.static(__dirname + '/public'))

// support json encoded bodies
app.use(bodyParser.json());
// support encoded bodies
app.use(bodyParser.urlencoded({ extended: true }));

console.log(api);    

app.post('/api/newFoo', api.newFoo);

在我的apiController文件中,我导出以下内容:

function newFoo(req, res, next) {

}

function getFoo(req, res, next) {

}

function newBar(req, res, next) {

}

function getBar(req, res, next) {

}

module.exports = {
  newFoo: newFoo,
  getFoo: getFoo,
  newBar: newBar,
  getBar: getBar
};

在将我的函数导出为字典时,我做错了什么,它们不被识别为函数指针?

当我为每个函数执行以下操作时,它工作正常:

module.exports.newFoo = function(req, res, next) {};

我的console.log(api.newFoo)的控制台输出是[Function]并给我typeof为“function”但是原始方法导致[newFoo:Function]返回typeof为“undefined”

1 个答案:

答案 0 :(得分:0)

  

server.js主文件在{node server.js}上运行

`const express = require('express')
const path = require('path')
const port = process.env.PORT || 3000
const app = express()

var bodyParser = require('body-parser');
var api = require('./apiController.js');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

console.log(api.getFoo); //--->[Function: newFoo] worked for me 
console.log(typeof(api.getFoo)); //===> function
app.post('/api/getFoo', api.getFoo);
app.listen(port) `
  

通过听一个端口尝试过邮差也对我有用

  

服务器上需要的apiController.js文件

function getFoo(req, res, next) {
console.log("2st function");
}
module.exports = {
  getFoo: getFoo
}
  • node -v 8.1.2
  • npm -v 5.0.2
  • expressjs -v 4.15.0