如何从express.js中的另一个函数调用一个函数?

时间:2016-05-24 09:08:54

标签: node.js express mean-stack meanjs

exports.usersignup= function(req, res) {
console.log('user signed up working')

}
exports.addcustomer= function(req, res) {
console.log('customer added')

}

我有两个函数,即exports.usersignup和exports.addcustomer。当我调用exports.usersignup函数时,它应调用exports.addcustomer 功能,它应该工作给定的逻辑我怎么能做到这一点任何人帮助我。请不要放弃投票我已经尝试但它不工作

2 个答案:

答案 0 :(得分:3)

这是一个天真的解决方案:

exports.usersignup = function (req, res) {
  console.log('usersignup')
  exports.addcustomer()
}

exports.addcustomer = function (req, res) {
  console.log('addcustomer')
}

更好的解决方案是使用Express middleware

// customer.js
// ...

exports.usersignup = function (req, res, next) {
  console.log('usersignup')
  next()
}
exports.addcustomer = function (req, res) {
  console.log('addcustomer')
}

// app.js
// ...

var express = require('express')
var customer = require('./customer.js')
var app = express()
app.post('/user', customer.usersignup, customer.addcustomer)

答案 1 :(得分:0)

在userignup函数中传递next变量,当你想调用addcustomer时,只需使用return next()语句