Is there any purpose of splitting up express and app? - javascript

I see these two lines in ( every ?) Express app.
const express = require('express');
const app = express();
I have to wonder if any parameters can be passed to express()?
Checked here and did not see any
https://expressjs.com/en/4x/api.html
Why are some methods on express() and some on app()?
It seems like they should be combined and have all methods on one object.

express does not take any parameters, no. The purpose of calling it is to create the app object, so the fact you have to call it does make sense, even without parameters.
Another way you often see that written is:
const app = require("express")();
It'll need to be separate again when using ESM, though.
import express from "express"; // Or similar
const app = express();
In a comment you've said:
For example, is there anything useful I can do with out creating app? Is there anything I can do only with express?
As far as I know, you have to have create at least one Application object to do anything useful with Express. Note that you don't have to create just one app. That's the typical use case, but there's no reason you can't create multiple apps running on different ports.
You may be wondering why express can't just give you an Application object directly from require. The reason is that modules are only loaded once and cached, so what you get from require is shared. So Express exports the express function, which you use to create the Application object (or objects, plural, if you want more than one).

Is there anything I can do only with express?
The reason for doing two separate lines like this:
const express = require('express');
const app = express();
instead of this:
const app = require('express')();
is that the express module has other methods on it that are sometimes needed such as:
express.static(...) // middleware for serving static files
express.json(...) // middleware for parsing json requests
express.urlencoded(...) // middleware for parsing urlencoded requests
express.Router(...) // constructor for a new Router object

Related

How is it possible to access and use the functions in express.js module?

If i want to create an express app i can write these two statements.
const express = require(“express“);
const app = express();
By using this "app" object I can access various functions within express() like get(),listen(),use() etc.
My Question is how these functions are returned by express() so that these are accessible using the "app" object. Does it return an object consisting of functions or there is some other way?
What is the sorcery behind this technology?
As you can see in the source code of express, app is just an object with methods like get, listen, use, and so on...
https://github.com/expressjs/express/blob/master/lib/application.js

Best practice for language sub domains in an Express server?

So I have a Node/Express server set up, and we are making the transition from subdirectories to sub domains for localisation, eg:
es.example.com // old way
www.example.com/es // new way
Doing this for a variety of reasons, but mostly to facilitate the preservation of JWT login state across the internationalised content. What is the best practice for allowing this in express when declaring routes?
If I have a route simply set up like this:
app.use('/search')
Then when I try to hit a route, eg www.example.com/es/search, I will just be redirected to www.example.com/search, the es will be stripped. However, this can be fixed like this:
app.use('*/search')
I'm sure this must have some negative implications though? How do people typically allow for prefixes in routes via Express?
If you are using Express 4, you can use modular routes to create a set of routes that can then be shared across your different locale codes. This will ensure that you only apply routes to specific locale codes rather than all possible words prior to your route (such as /fakePath/search).
// routes.js
var express = require('express');
var router = express.Router();
router.use('/search');
module.exports = router;
// index.js
var routes = require('./routes');
app.use('/en', routes);
app.use('/es', routes);
// ...

Express.js - Helmet.js and other middleware, and mounted applications?

In a recent learning project, I'm using three Express.js applications to separate the project into more manageable pieces.
One application is the "primary" app, the one that listens for connections. The other two are mounted at specific routes on the primary app.
Is it sufficient to call app.disable('x-powered-by'); on the primary app to disable the X-Powered-By header, or would this need to be done in each of the mounted apps as well?
Similarly, I'm looking into using Helmet.js to try and add a bit of additional security to the entire project. Is it enough to include any middleware from Helmet.js on the primary app, or would these also need to be defined in the mounted apps?
I don't feel as though I understand how some settings and middleware affect mounted Express.js apps, and would appreciate further explanation from anyone with more experience.
Edit: After playing with app.disable('x-powered-by') and examining responses from the server, the X-Powered-By header appears if I don't disable it in both the primary application instance and any mounted application instances. I therefore presume Helmet.js middleware operate the same way, but I'm not 100% certain. Can anyone confirm if this is the expected behavior?
You're right about everything you've said.
It sounds like you're doing something like this:
var express = require('express')
var mainApp = express()
var miniAppA = express()
var miniAppB = express()
mainApp.use('/a', miniAppA)
mainApp.use('/b', miniAppB)
mainApp.listen(3000)
This is an okay way to do things, but headers will be overridden in the sub-apps, as you saw.
You can use Express 4's routers feature to mitigate this. Instead of making new mini-apps with express(), you can use express.Router(). These are Express apps with fewer features (for example, they don't set headers the same way).
Something like this might solve your issue:
var express = require('express')
var mainApp = express()
var miniAppA = express.Router()
var miniAppB = express.Router()
mainApp.use('/a', miniAppA)
mainApp.use('/b', miniAppB)
mainApp.listen(3000)

node.js: How to look up an API?

I am a new practicer of Node.js. I have a pretty silly problem. When I use packages or some code written by other people, I cannot find out where the definitions of components. Right now, I am struggling for searching for request.files used in Express.js. My questions are, if I don't study the source:
Where should I go to see the formal API document on request.files?
How should I identify the type of a req object: http.request or expressjs.request?
What are optimal ways to find an API's definition?
Express has pretty good documentation. Take a look at what the request object has by default. This of course can be modified by middleware. In this case, you're looking for req.files, which could be added by a few different middleware. A Google search for express req.files shows expressjs/multer as the fourth result. Taking a look at that we see:
var express = require('express')
var multer = require('multer')
var app = express()
app.use(multer({ dest: './uploads/'}))
You can access the fields and files in the request object:
console.log(req.body)
console.log(req.files)
So in this case, the multer middleware will add the ability to handle uploaded files, and make those files available at req.files.

Specifying routes by subdomain in Express using vhost middleware

I'm using the vhost express/connect middleware and I'm a bit confused as to how it should be used. I want to have one set of routes apply to hosts with subdomains, and another set to apply for hosts without subdomains.
In my app.js file, I have
var app = express.createServer();
app.use...(middlware)...
app.use(express.vhost('*.host', require('./domain_routing')("yes")));
app.use(express.vhost('host', require('./domain_routing')("no")));
app.use...(middlware)...
app.listen(8000);
and then in domain_routing.js:
module.exports = function(subdomain){
var app = express.createServer();
require('./routes')(app, subdomain);
return app;
}
and then in routes.js I plan to run sets of routes, dependent on whether the subdomain variable passed in is "yes" or "no".
Am I on the right track or is this not how you use this middleware? I'm a bit confused on the fact that there are two app server instances being created (as that's how examples on the web seem to do things). Should I instead pass in the original app server instance and just use that instead of creating a separate one instead the subdomain router?
Yes, you are on the right track. You should have a different server instance for each of the vhost. Be it a http.Server or express app.
If you pass the original app, a request you sent to the vhost will be emitted to the original app. So, unless the vhost has paths which are not used in original server, it will get response as if the request was sent to original server.
From the connect docs
connect()
.use(connect.vhost('foo.com', fooApp))
.use(connect.vhost('bar.com', barApp))
.use(connect.vhost('*.com', mainApp))

Categories

Resources