Is express() function used in the second statement a global function?.
Where can I find its declaration?. I could not find it in my project folder.
var express = require('express');
var app = express();
var fs = require("fs");
Here is what you are doing:
// creating a variable named express and storing return value of require function
// require is a nodejs function, in this case it is called with parameter called express which loads express module
var express = require('express');
// Executing the function stored in express variable
// And storing the result into app variable
var app = express();
So, where does the express comes, you are declaring it in line 1. var express = require('express') is just a convention, you can use any valid variable name. Following would also work:
var expServer = require('express');
var app = expServer();
Express is a npm module and you need to import it in order to use it, jsut like other npm packages.
Where can I find its declaration?. I could not find it in my project folder.
Its declaration is in the node_modules directory and you don't have to do anything with it.
Here is the example for using express and creating a server from it.
var express = require('express');
var app = express();
app.get('/', function(req, res){
res.send("Hello world!");
});
app.listen(3000);
Related
I have an Express app whose server.js file has maybe 30 GET and POST endpoints, like this:
const express = require('express');
const app = express();
const http_port = 8000;
app.listen(http_port,()=>{
console.log(`app listening on port ${http_port}`);
});
app.get('/create_something',function(req,res){
createSomething();
res.send('create');
});
app.post('/update_something',function(req,res){
updateSomething();
res.send('update');
});
//and so on for 30 more endpoints
For ease of maintenance, I want to break this set of endpoints up into different files, e.g. video.js and audio.js.
Thinking this solution might help, I created another file other_route.js:
var express=require('express');
var router=express.Router();
router.get('/other_route_endpoint',function(req,res){
res.send('other_route_endpoint');
});
module.exports.router=router;
and then including this in server.js by changing my initial declarations to:
const express = require('express');
const app = express();
const http_port = 8000;
var router=express.Router();
router.use('/other_route',require('./other_route').router);
But when I visit myserver.com:8000/other_route_endpoint, I get this error:
Cannot GET /other_route_endpoint
How can I add in endpoints from other files into server.js, so I can move some of its many endpoints into these subfiles?
First, your main file should not be using a router. Change the line to app.use('/other_route',require('./other_route').router);.
Second: each path you set with router.use in the routing file will be relative to the path specified in app.use. See https://expressjs.com/en/guide/routing.html#express-router
For example, if you have this in your main file
app.use('/foo', require('./bar.js'));
And this in bar.js
router.get('/bar', /* do something */);
Then the corresponding endpoint would be /foo/bar.
I'm building a node.js server and my folder structure looks like this:
server.js
app/routes.js
app/routes/users.js
My problem is that i'm not sure how can i use the app variable inside the users.js file. Do i have to require and setup express again in this file or is there a better/easier way to do it? Here is my sample code(just the bare minimum to understand my problem):
server.js
// Include our packages in our main server file
var express = require('express');
var stormpath = require('express-stormpath');
var app = express();
// Init Stormpath for user management and authentication
app.use(stormpath.init(app));
// Load routes
require('./app/routes')(app);
// Start the server
app.listen(process.env.PORT);
// Stormpath will let you know when it's ready to start authenticating users.
app.on('stormpath.ready', function () {
console.log('Your server is running on port ' + port + '.');
});
app/routes.js
// Import dependencies
const express = require('express');
const stormpath = require('express-stormpath');
// Export the routes for our app to use
module.exports = function(app) {
// Create API group routes
const apiRoutes = express.Router();
// User management: get users, invite users, view user profile
var UsersRoute = require('./routes/users');
apiRoutes.get('/memberinfo', stormpath.loginRequired, UsersRoute.memberInfo);
// Set url for API group routes
app.use('/', apiRoutes);
};
app/routes/users.js
// Protected route test
module.exports.memberInfo = function(req, res){
//how do i access the "app" here?
res.status(200).send({ user: req.user });
}
In your .memberInfo method, you can use req.app to access the app object that is associated with that request.
In cases where you aren't passed a req object that you can use in this way, then you need to initialize the module by calling a method on it and passing it the app object and the module can then store the app object locally so it can use it when desired.
I'm using express in my app.js I set something like this
var express = require('express');
var app = express();
app.set('myVar', 'hello');
then in my controller I want to get the value. I do
var express = require('express');
var app = express();
console.log(app.get('myVar')) // undefineded
Any idea why?
Your controller creates a new, fresh instance of Express. If you want to be able to share variables, you need to pass the instance from app.js to your controller:
// app.js
var express = require('express');
var app = express();
app.set('myVar', 'hello');
require('./controller')(app);
// controller.js
module.exports = function(app) {
console.log(app.get('myVar'));
};
EDIT: judging by the comments, the issue isn't so much passing app around, but moving parts of the application to separate modules. A common setup to enable that would look like this:
// app.js
var express = require('express');
var app = express();
app.set('myVar', 'hello');
app.use('/api', require('./controller/auth'));
// controller/auth.js
var express = require('express');
var router = express.Router();
router.get('/', function(req, res) {
console.log(req.app.get('myVar'));
return res.send('hello world');
});
module.exports = router;
In your example you are instantiating a second app that you then try to get the value from. You need to get from the exact same object:
var express = require('express');
var app = express();
app.set('foo', 'bar');
app.get('foo');
If you are new to express, you can use the cli generator to scaffold out an application that shows you a sane pattern how to use the same express instance throughout your whole application.
I tried to separate my node routing into two parts: HTML/App and REST. Here is what I've done:
app.js:
var appPort = process.env.PORT || 80;
var express = require('express');
var http = require('http');
var appRouter = require('./routes/index');
var restRouter = require('./routes/rest');
var app = express();
var srv = http.createServer(app);
app.set('port', appPort);
app.set('view engine', 'jade');
app.use(express.static(path.join(__dirname, 'public')));
app.use('/api/rest/', restRouter); // this seems not working .. I never get the expected response
app.use('/', appRouter); // I get this even with localhost/api/rest/...
var server = srv.listen(app.get('port'), function() {
debug('Express server listening ' + server.address().address + ':' + server.address().port);
});
index.js:
var express = require('express');
var router = express.Router();
router.get('/*', function (req, res) {
res.send('HOME')
});
module.exports = router;
rest.js
var express = require('express');
var router = express.Router();
router.get('/api/rest/*', function(req, res) {
res.send('REST API');
});
module.exports = router;
My questions:
1. It's possible in general to build multiple routers in this way?
2. Does the sequence of get.use matter, and/or do I have to deal with 'next'?
3. In case I would like to access a database inside the router can I hand over a parameter like this:
// ...
var client = new pg.Client(dbConnection);
// ...
app.use('/', appRouter(client));
1) It is possible to build multiple routers this way.
Because you are using this:
app.use('/api/rest/', restRouter);
your route calls in rest.js will be relative to /api/rest/ which means your code should be modified in rest.js to look like this:
router.get('*', function(req, res) {
res.send('REST API');
});
I would also encourage you to see the Express multi-router example on GitHub. It illustrates this point very clearly by showing a REST app with versioned routes.
2) The order of things matter
See the Express documentation for app.use and you will note:
Middleware functions are executed sequentially, therefore the order of
middleware inclusion is important.
If you reverse the order of your app.use calls, the router.get('/*', function (req, res) { line in index.js will catch everything before you get to other routes...defeating your purpose.
Also, if you don't call next, Express has no way to know that you are done or even that you want to continue to the next middleware or route.
3) The database question is a modules/scope question
This is more of a scope question than an Express question. I'd suggest looking up some of the excellent writing about javascript scope and also on how Node handles modules.
My requires:
//app.js Socket IO Test
var app = require('express').createServer(),
redis = require('socket.io/node_modules/redis'),
io = require('socket.io').listen(app);
My error:
Warning: express.createServer() is deprecated, express
applications no longer inherit from http.Server,
please use:
var express = require("express");
var app = express();
How do I modify my declarations to avoid this error? I understand this methodology is now deprecated for Express, just not sure what it needs to be changed to...
Thanks in advance!
Simply replace var app = require('express').createServer() with:
var express = require("express");
var app = express();