Routing in Javascript (multiple files)

71 Views Asked by At

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}})

2

There are 2 best solutions below

1
On BEST ANSWER

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
0
On

I think you should require api.js by using var val = require("./api.js") which I guess is the file name, but be sure to add ./ for requiring of files you created.

Routes.js

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)})

api.js

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