javascriptangularjsjs-routes

Routing in Javascript (multiple files)


I am accessing api.js from Routes.js but I am getting an error that function my_function_in_api is not defined. My code is as follows, please advise where is the problem:

Routes.js

var val = require('file name')

modules.exports = function(app){ app.get('/test_function',function(req,res){ val.my_function_in_api(req,res)})

api.js

module.exports = (function() { return { my_function_in_api: function(req,res) { // do something}})


Solution

  • In addition to Fischer's answer, you are exporting from api.js as a function, so in Routes.js you need to actually call the default function exported from api.js:

    val().my_function_in_api // etc
    

    Full code:

    var val = require('./api.js') //observe the "./" before the api.js
    
    modules.exports = function(app){
    app.get('/test_function',function(req,res){
    val().my_function_in_api(req,res)}) // notice the parentheses after val