简体   繁体   English

Javascript module.export函数指针的结构

[英]Javascript module.export struct of function pointers

I'm getting the following when I run my node app: 当我运行节点应用程序时,我得到以下内容:

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

I have the following in my app.js file: 我的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);

And in my apiController file, I export the following: 在我的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
};

What am I doing wrong in exporting my functions as a dictionary, where they are not being recognized as function pointers? 将我的函数导出为字典时,我做错了什么?它们不被识别为函数指针?

It works fine when I do the following for each function: 当我为每个函数执行以下操作时,它工作正常:

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

And my console output for console.log(api.newFoo) is [Function] and gives me typeof as "function" but the original method in question results in [newFoo : Function] which returns typeof as "undefined" 我的console.log(api.newFoo)的控制台输出是[Function]并给我typeof为“function”但是原始方法导致[newFoo:Function]返回typeof为“undefined”

server.js main file runing on {node server.js} 运行在{node server.js}上的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) `

by listening on an port have tried with postman also it worked for me 通过听一个端口尝试过邮差,它也适合我


apiController.js file this is requiring on the server 这是服务器上需要的apiController.js文件

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

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

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