app.get is undefined (node.js) - javascript

In my app.js file I do the following...
var app = module.exports = express();
Then in my register.js file I am using get to render a page in the following way...
var module = require('../app');
module.app.get('/register', function (req, res) {
res.render('register.jade', { title: 'register' });
});
But I get the error that get cannot be used with app because it is undefined
If I change my get function to the following, everything works fine...
exports.register = function (req, res) {
res.render('register.jade', { title: 'register' });
};
and change my app.js to...
app.get('/register', reg.register);
... it will work.
But I want to be able to export app so I can use it in other routes. How do I properly export it?
EDIT
I just realized the proper way to to require the module is using var app = require('./app');.
The path I mentioned before is wrong.
But now I get an error cannot find module ./app, I have no idea why.

only things assigned to module.exports are visible outside of that JavaScript file. In your case that is returned value of express(). There is no module.app exported. Also, stop using module as variable name, because its one of the globals injected to the JavaScript file.
Better do something more clear and hand control to server script, which in turn will call all required setup functions on server run:
Structure:
project
|_controllers
| |_login.js
| |_register.js
|_routes.js
|_app.js
controllers/login.js :
/**
* Login user.
* #param req - express Request.
* #param res - express Response.
* #param next - calls next middleware.
*/
function login(req,res,next){
res.send("Login!");
}
// exports
module.exports = login;
controllers/register.js :
/**
* Register user.
* #param req - express Request.
* #param res - express Response.
* #param next - calls next middleware.
*/
function login(req,res,next){
res.send("Register!");
}
// exports
module.exports = register;
routes.js:
/**
* routes module.
*/
var routes = {};
/**
* Setup app routes.
* #param app - Express app instance.
*/
routes.setup = function setup(app){
app.post('/register',require('./controllers/register'));
app.post('/login',require('./controllers/login'));
}
// exports
module.exports = routes;
app.js:
var express = require('express');
var routes= require('./routes');
// init app
var app = express();
// setup routes
routes.setup(app);
// start server
app.listen(8080);

First thing I wanna say is what module.exports=... and exports.something=... do. module.exports is the object that would be import after require it. Let's say there is a file named X.js :
var A = {
name:'A'
};
module.exports = A;
Now we can import it in other file, suppose we have a file named Y.js :
var A = require('pathToX/X');
console.log(A.name);
So, in your code module.exports = express();, the object you've exported is the "express()" itself. Your should use it in other files (for example, your register.js file) in this way :
var module = require('../app');
module.get('/register', function (req, res) {
res.render('register.jade', { title: 'register' });
});
That is, when you call require('../app'), what you got is the express(). So your code module.app.get is equals to express().app.get, of cause there is no app property in express().
Besides, the module is predefined in node js, please don't use it as a variable name, you can change your register.js file to
var app = require('../app');
app.get('/register', function (req, res) {
res.render('register.jade', { title: 'register' });
});
And this is true : exports===module.exports, so you did the right way to import register in your code app.get('/register', reg.register);.
One more thing, exports={name:'A'} is NOT equals to module.exports={name:'A'}, that is pretty straightforward, exports is just a variable link to module.exports, change the exports link itself won't change module.exports.

In your app.js, try something more like:
module.exports = {
app: express()
}
Then when you do var module = require('./app'), module will contain an object which has an app property.
Note that I don't know what express() does, but I am assuming it is returning an object that has a get() function on it.

try this
//app.js
var express = require('express');
var app = module.exports = express();
//register.js
var module = require('./app.js');
//var http = require('http');
//var server = http.createServer(module);
module.get('/register', function(req,res,next) {
// body...
console.log("register");
});
//server.listen(1338);

Related

How to import object to another file?

I'm using Node.js to build a web application.
I have two files. Server.js - where I call the server to go online etc. And the other one is a file which includes a big object with data. I imported the file with data into server.js, I get the object in postman when I set the website to be live. But I can't dive inside the object to get the data inside the object. The error I'm getting says that the variable where my data is stored is not defined.
I think the fix is to import albumsData variable into server.js, but im completely stuck and can't find how to do it. If anyone has any idea, please share.
albumsData.js
const express = require('express');
const router = express.Router();
let albumsData = {
filled with data
}
router.get('/albumData', (req, res) => {
res.send(albumsData);
});
module.exports = router;
Server.js
app.use(require('./api/albumData/unikkatilData'))
app.use((req, res) => {
res.status(404)
.send(albumsData)
});
app.listen(4000, () => {
console.log('hello worldd')
})
If you want the albumsData object then you can do it like this:
In you albumsData.js file:
const albumsData = {
// Bunch of data
}
module.exports = albumsData
Then in your server.js file:
const albumData = require('./api/albumsData') // Make sure this path points directly to the albumsData.js file
move enter code here to new file (ex utils.js)
and export it exports.albumsData = albumsData; then you can call it
with const utils = require('./utils') ; utils.albumsData

How to exports many mongoose models modules in node.js

I have 2 models like this
const Db = mongoose.model('db', dbSchema);
const Beacon = mongoose.model('beacon', dbSchema2);
Now I want to export them. First I export Db and everything is fine. I can do an HTTP request with it.
module.exports = Db;
However, when I try to export ´the 2nd one outside, it stops functioning. The functions below will return a blank JSON file as a response.
module.exports = Db;
module.exports = Beacon;
This won't work either. It returns an error handler saying all my functions in the handler is not function.
module.exports = {
Db, Beacon
}
This is the function on the file I import the models.
router.get('/data/:id', function(req, res, next) {
Db.findOne({ _id: req.params.id }).then(function(db) {
res.send(db);
});
}
The return from the handler is Db.findOne is not a function.
Is there any way to export them both? Thank you.
Here is the importing on another file
const Db = require('./db.js');
const Beacon = require('.db.js');
This should work:
Exporting in one file
module.exports = { Db, Beacon };
Then, importing in another file
const { Db, Beacon } = require('path-to-db.js');
// use them
Db.doSomething();
Beacon.doSomethingElse();
Notice that this uses the ECMAS 6 Destructuring Assignment (additional info on MDN)

exported function returns 'undefined' when called inside app.get()

I defined a sequelize model in a file named courses.js as such:
const Sequelize = require('sequelize');
var connection = new Sequelize( ... );
module.exports = Courses = connection.define('courses', { ... });
Then required it in a file called coursescontroller.js:
const Courses = require('../models/courses');
function find_records() {
Courses.findAll().then(function(records) {
return records;
});
}
module.exports.find_records = find_records;
Then finally required the function in the express router file and used it as such:
var express = require('express');
var router = express.Router();
var controller = require('../controllers/coursescontroller');
router.get('/', function(req, res, next) {
var records = controller.find_records();
console.log(records); // console shows undefined
res.send(records); // doesn't send anything back when I make a get request
});
Could you please help me get the find_records() function to work properly and return the database records when called inside the get request callback function.

Koa pass data from server to client

I want to pass through some environment variables from a Koa server to the client. In express I could do something like res.render('index', { data: 'someData' }); and then I could access data. In Koa I can't see how to do this. It mentions using context.state but I can't find any example of how to retrieve this in the client.
You can do something similar in Koa, you just need to use the right middleware. Try out koa-views if you're using one of the supported engines.
Here is a full example (this example assumes you're using Koa v1 and EJS as your templating engine):
app.js
const Koa = require('koa')
const views = require('koa-views')
const router = require('./routes')
const app = new Koa()
app.use(views(__dirname + '/views', { extension: 'ejs' }))
app.use(router.routes())
app.use(router.allowedMethods())
app.listen(3000)
routes.js
const router = require('koa-router')()
router.get('/', function * () {
yield this.render('index', { title: 'Home' })
})
router.get('/about', function * () {
yield this.render('about', { title: 'About' })
})
module.exports = router
Just change the extension argument you pass to the middleware based on which templating engine you are using.

Hapi showing undefined variable inside handler

I'm using Hapi.js for a project and a config variable that I'm passing to my handler is coming up as undefined when I call my route. What am I doing wrong?
server.js
var Hapi = require('hapi');
var server = new Hapi.Server('0.0.0.0', 8080);
// passing this all the way to the handler
var config = {'number': 1};
var routes = require('./routes')(config);
server.route(routes);
server.start();
routes.js
var Home = require('../controllers/home');
module.exports = function(config) {
var home = new Home(config);
var routes = [{
method: 'GET',
path: '/',
handler: home.index
}];
return routes;
}
controllers/home.js
var Home = function(config) {
this.config = config;
}
Home.prototype.index = function(request, reply) {
// localhost:8080
// I expected this to output {'number':1} but it shows undefined
console.log(this.config);
reply();
}
module.exports = Home;
The issue is with the ownership of this. The value of this within any given function call is determined by how the function is called not where the function is defined. In your case above this was referring to the global this object.
You can read more on that here: What does "this" mean?
In short the solution to the problem is to change routes.js to the following:
var Home = require('../controllers/home');
module.exports = function(config) {
var home = new Home(config);
var routes = [{
method: 'GET',
path: '/',
handler: function(request, reply){
home.index(request, reply);
}
}];
return routes;
}
I've tested this and it works as expected. On a side note, you're missing out on a lot of hapi functionality by structuring your code in this way, I generally use plugins to register routes instead of requiring all routes as modules and using server.route().
See this project, feel free to open an issue if you have further questions on this: https://github.com/johnbrett/hapi-level-sample

Categories