0

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

lealceldeiro
  • 14,342
  • 6
  • 49
  • 80
Tabz
  • 137
  • 1
  • 11
  • Are your importing `my_function_in_api` from `api.js` with `var val = require('file name')` ?? if so, should not it be ``var val = require('api.js')` ?? On the other hand... is this AngularJS(1.x) or Angular (2+)?? – lealceldeiro Feb 09 '18 at 14:26

2 Answers2

0

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}})
antzshrek
  • 9,276
  • 5
  • 26
  • 43
Swam Didam
  • 61
  • 9
0

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
wilsonhobbs
  • 941
  • 8
  • 18