簡體   English   中英

Javascript module.export函數指針的結構

[英]Javascript module.export struct of function pointers

當我運行節點應用程序時,我得到以下內容:

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”

運行在{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) `

通過聽一個端口嘗試過郵差,它也適合我


這是服務器上需要的apiController.js文件

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM