Express interview questions
16 questions with answers. 39 open jobs in India ask for Express.
Why doesn't adding CORS headers to an OPTIONS route allow browsers to access my API?
I found the easiest way is to use the node.js package cors. The simplest usage is:
var cors = require('cors') var app = express() app.use(cors())There are, of course many ways to configure the behaviour to your needs; the page linked above shows a number of examples.
From Stack Overflow: asked by mikong, answered by Wayne Maurer (CC BY-SA 3.0)
Express.js - app.listen vs server.listen
The second form (creating an HTTP server yourself, instead of having Express create one for you) is useful if you want to reuse the HTTP server, for example to run
socket.iowithin the same HTTP server instance:var express = require('express'); var app = express(); var server = require('http').createServer(app); var io = require('socket.io').listen(server); ... server.listen(1234);However,
app.listen()also returns the HTTP server instance, so with a bit of rewriting you can achieve something similar without creating an HTTP server yourself:var express = require('express'); var app = express(); // app.use/routes/etc... var server = app.listen(3033); var io = require('socket.io').listen(server); io.sockets.on('connection', function (socket) { ... });From Stack Overflow: asked by Tamas, answered by robertklep (CC BY-SA 3.0)
What does body-parser do with express?
Edit: in 2019-april-2 in express@4.16.0 the body-parser middleware is included in express, so you don't need to install body-parser separately anymore. for more details see this
OLD:
To handle
HTTP POSTrequests in Express.js version 4 and above, you need to install the middleware module calledbody-parser.body-parserextracts the entire body portion of an incoming request stream and exposes it onreq.body.The middleware was a part of Express.js earlier but now you have to install it separately.
This
body-parsermodule parses the JSON, buffer, string and URL encoded data submitted usingHTTP POSTrequest. Installbody-parserusing NPM as shown below.npm install body-parser --saveFrom Stack Overflow: asked by jiten, answered by Malatesh Patil (CC BY-SA 4.0)
What is Express.js?
This is over simplifying it, but Express.js is to Node.js what Ruby on Rails or Sinatra is to Ruby.
Express 3.x is a light-weight web application framework to help organize your web application into an MVC architecture on the server side. You can use a variety of choices for your templating language (like EJS, Jade, and Dust.js).
You can then use a database like MongoDB with Mongoose (for modeling) to provide a backend for your Node.js application. Express.js basically helps you manage everything, from routes, to handling requests and views.
Redis is a key/value store -- commonly used for sessions and caching in Node.js applications. You can do a lot more with it, but that's what I'm using it for. I use MongoDB for more complex relationships, like line-item <-> order <-> user relationships. There are modules (most notably connect-redis) that will work with Express.js. You will need to install the Redis database on your server.
Here is a link to the Express 3.x guide: https://expressjs.com/en/3x/api.html
From Stack Overflow: asked by vinod, answered by chovy (CC BY-SA 4.0)
Understanding passport serialize deserialize
- Where does
user.idgo afterpassport.serializeUserhas been called?
The user id (you provide as the second argument of the
donefunction) is saved in the session and is later used to retrieve the whole object via thedeserializeUserfunction.serializeUserdetermines which data of the user object should be stored in the session. The result of the serializeUser method is attached to the session asreq.session.passport.user = {}. Here for instance, it would be (as we provide the user id as the key)req.session.passport.user = {id: 'xyz'}- We are calling
passport.deserializeUserright after it where does it fit in the workflow?
The first argument of
deserializeUsercorresponds to the key of the user object that was given to thedonefunction (see 1.). So your whole object is retrieved with help of that key. That key here is the user id (key can be any key of the user object i.e. name,email etc). IndeserializeUserthat key is matched with the in memory array / database or any data resource.The fetched object is attached to the request object as
req.userVisual Flow
passport.serializeUser(function(user, done) { done(null, user.id); }); │ │ │ └─────────────────┬──→ saved to session │ req.session.passport.user = {id: '..'} │ ↓ passport.deserializeUser(function(id, done) { ┌───────────────┘ │ ↓ User.findById(id, function(err, user) { done(err, user); }); └──────────────→ user object attaches to the request as req.user });From Stack Overflow: asked by Anubhav, answered by A.B (CC BY-SA 4.0)
- Where does
Differences between express.Router and app.get?
app.js
var express = require('express'), dogs = require('./routes/dogs'), cats = require('./routes/cats'), birds = require('./routes/birds'); var app = express(); app.use('/dogs', dogs); app.use('/cats', cats); app.use('/birds', birds); app.listen(3000);dogs.js
var express = require('express'); var router = express.Router(); router.get('/', function(req, res) { res.send('GET handler for /dogs route.'); }); router.post('/', function(req, res) { res.send('POST handler for /dogs route.'); }); module.exports = router;When
var app = express()is called, an app object is returned. Think of this as the main app.When
var router = express.Router()is called, a slightly different mini app is returned. The idea behind the mini app is that each route in your app can become quite complicated, and you'd benefit from moving all that code into a separate file. Each file's router becomes a mini app, which has a very similar structure to the main app.In the example above, the code for the /dogs route has been moved into its own file so it doesn't clutter up the main app. The code for /cats and /birds would be structured similarly in their own files. By separating this code into three mini apps, you can work on the logic for each one in isolation, and not worry about how it will affect the other two.
If you have code (middleware) that pertains to all three routes, you can put it in the main app, before the
app.use(...)calls. If you have code (middleware) that pertains to just one of those routes, you can put it in the file for that route only.From Stack Overflow: asked by nelson687, answered by Nocturno (CC BY-SA 4.0)
What is the parameter "next" used for in Express?
It passes control to the next matching route. In the example you give, for instance, you might look up the user in the database if an
idwas given, and assign it toreq.user.Below, you could have a route like:
app.get('/users', function(req, res) { // check for and maybe do something with req.user });Since /users/123 will match the route in your example first, that will first check and find user
123; then/userscan do something with the result of that.Route middleware is a more flexible and powerful tool, though, in my opinion, since it doesn't rely on a particular URI scheme or route ordering. I'd be inclined to model the example shown like this, assuming a
Usersmodel with an asyncfindOne():function loadUser(req, res, next) { if (req.params.userId) { Users.findOne({ id: req.params.userId }, function(err, user) { if (err) { next(new Error("Couldn't find user: " + err)); return; } req.user = user; next(); }); } else { next(); } } // ... app.get('/user/:userId', loadUser, function(req, res) { // do something with req.user }); app.get('/users/:userId?', loadUser, function(req, res) { // if req.user was set, it's because userId was specified (and we found the user). }); // Pretend there's a "loadItem()" which operates similarly, but with itemId. app.get('/item/:itemId/addTo/:userId', loadItem, loadUser, function(req, res) { req.user.items.append(req.item.name); });Being able to control flow like this is pretty handy. You might want to have certain pages only be available to users with an admin flag:
/** * Only allows the page to be accessed if the user is an admin. * Requires use of `loadUser` middleware. */ function requireAdmin(req, res, next) { if (!req.user || !req.user.admin) { next(new Error("Permission denied.")); return; } next(); } app.get('/top/secret', loadUser, requireAdmin, function(req, res) { res.send('blahblahblah'); });Hope this gave you some inspiration!
From Stack Overflow: asked by Menztrual, answered by Asherah (CC BY-SA 4.0)
Node.js / Express.js - How does app.router work?
Note: This describes how Express worked in versions 2 and 3. See the end of this post for information about Express 4.
staticsimply serves files (static resources) from disk. You give it a path (sometimes called the mount point), and it serves the files in that folder.For example,
express.static('/var/www')would serve the files in that folder. So a request to your Node server forhttp://server/file.htmlwould serve/var/www/file.html.routeris code that runs your routes. When you doapp.get('/user', function(req, res) { ... });, it is therouterthat actually invokes the callback function to process the request.The order that you pass things to
app.usedetermines the order in which each middleware is given the opportunity to process a request. For example, if you have a file calledtest.htmlin your static folder and a route:app.get('/test.html', function(req, res) { res.send('Hello from route handler'); });Which one gets sent to a client requesting
http://server/test.html? Whichever middleware is given tousefirst.If you do this:
app.use(express.static(__dirname + '/public')); app.use(app.router);Then the file on disk is served.
If you do it the other way,
app.use(app.router); app.use(express.static(__dirname + '/public'));Then the route handler gets the request, and "Hello from route handler" gets sent to the browser.
Usually, you want to put the router above the static middleware so that a accidentally-named file can't override one of your routes.
Note that if you don't explicitly
usetherouter, it is implicitly added by Express at the point you define a route (which is why your routes still worked even though you commented outapp.use(app.router)).A commenter has brought up another point about the order of
staticandrouterthat I hadn't addressed: the impact on your app's overall performance.Another reason to
userouterabovestaticis to optimize performance. If you putstaticfirst, then you'll hit the hard drive on every single request to see whether or not a file exists. In a quick test, I found that this overhead amounted to ~1ms on an unloaded server. (That number is much likely to be higher under load, where requests will compete for disk access.)With
routerfirst, a request matching a route never has to hit the disk, saving precious milliseconds.Of course, there are ways to mitigate
static's overhead.The best option is to put all of your static resources under a specific folder. (IE
/static) You can then mountstaticto that path so that it only runs when the path starts with/static:app.use('/static', express.static(__dirname + '/static'));In this situation, you'd put this above
router. This avoids processing other middleware/the router if a file is present, but to be honest, I doubt you'll gain that much.You could also use
staticCache, which caches static resources in-memory so that you don't have to hit the disk for commonly requested files. (Warning:staticCachewill apparently be removed in the future.)However, I don't think
staticCachecaches negative answers (when a file does not exist), so it doesn't help if you've putstaticCacheaboverouterwithout mounting it to a path.Read the rest at the sourceFrom Stack Overflow: asked by Aust, answered by josh3736 (CC BY-SA 4.0)
What is NODE_ENV and how to use it in Express?
NODE_ENVis an environment variable made popular by the express web server framework. When a node application is run, it can check the value of the environment variable and do different things based on the value.NODE_ENVspecifically is used (by convention) to state whether a particular environment is a production or a development environment. A common use-case is running additional debugging or logging code if running in a development environment.Accessing NODE_ENV
You can use the following code to access the environment variable yourself so that you can perform your own checks and logic:
var environment = process.env.NODE_ENVAssume production if you don't recognise the value:
var isDevelopment = environment === 'development' if (isDevelopment) { setUpMoreVerboseLogging() }You can alternatively using express'
app.get('env')function, but note that this is NOT RECOMMENDED as it defaults to"development", which may result in development code being accidentally run in a production environment - it's much safer if your app throws an error if this important value is not set (or if preferred, defaults to production logic as above).Be aware that if you haven't explicitly set
NODE_ENVfor your environment, it will beundefinedif you access it fromprocess.env, there is no default.Setting NODE_ENV
How to actually set the environment variable varies from operating system to operating system, and also depends on your user setup.
If you want to set the environment variable as a one-off, you can do so from the command line:
- linux & mac:
export NODE_ENV=production - windows:
$env:NODE_ENV = 'production'
In the long term, you should persist this so that it isn't unset if you reboot - rather than list all the possible methods to do this, I'll let you search how to do that yourself!
Convention has dictated that there are two 'main' values you should use for
NODE_ENV, eitherproductionordevelopment, all lowercase. There's nothing to stop you from using other values, (test, for example, if you wish to use some different logic when running automated tests), but be aware that if you are using third-party modules, they may explicitly compare with'production'or'development'to determine what to do, so there may be side effects that aren't immediately obvious.Finally, note that it's a really bad idea to try to set
NODE_ENVfrom within a node application itself - if you do, it will only be applied to the process from which it was set, so things probably won't work like you'd expect them to. Don't do it - you'll regret it.From Stack Overflow: asked by TIMEX, answered by Ed_ (CC BY-SA 4.0)
- linux & mac:
Difference between res.send and res.json in Express.js
The methods are identical when an object or array is passed, but
res.json()will also convert non-objects, such asnullandundefined, which are not valid JSON.The method also uses the
json replacerandjson spacesapplication settings, so you can format JSON with more options. Those options are set like so:app.set('json spaces', 2); app.set('json replacer', replacer);And passed to a
JSON.stringify()like so:JSON.stringify(value, replacer, spacing); // value: object to format // replacer: rules for transforming properties encountered during stringifying // spacing: the number of spaces for indentationThis is the code in the
res.json()method that theres.send()method doesn't have:var app = this.app; var replacer = app.get('json replacer'); var spaces = app.get('json spaces'); var body = JSON.stringify(obj, replacer, spaces);The method ends up as a
res.send()in the end:this.charset = this.charset || 'utf-8'; this.get('Content-Type') || this.set('Content-Type', 'application/json'); return this.send(body);From Stack Overflow: asked by Dhanu Gurung, answered by hexacyanide (CC BY-SA 4.0)
Difference between app.use and app.get in express.js
app.use()is intended for binding middleware to your application. Thepathis a "mount" or "prefix" path and limits the middleware to only apply to any paths requested that begin with it. It can even be used to embed another application:// subapp.js var express = require('express'); var app = modules.exports = express(); // ...// server.js var express = require('express'); var app = express(); app.use('/subapp', require('./subapp')); // ...By specifying
/as a "mount" path,app.use()will respond to any path that starts with/, which are all of them and regardless of HTTP verb used:GET /PUT /fooPOST /foo/bar- etc.
app.get(), on the other hand, is part of Express' application routing and is intended for matching and handling a specific route when requested with theGETHTTP verb:GET /
And, the equivalent routing for your example of
app.use()would actually be:app.all(/^\/.*/, function (req, res) { res.send('Hello'); });(Update: Attempting to better demonstrate the differences.)
The routing methods, including
app.get(), are convenience methods that help you align responses to requests more precisely. They also add in support for features like parameters andnext('route').Within each
app.get()is a call toapp.use(), so you can certainly do all of this withapp.use()directly. But, doing so will often require (probably unnecessarily) reimplementing various amounts of boilerplate code.Examples:
For simple, static routes:
app.get('/', function (req, res) { // ... });vs.
app.use('/', function (req, res, next) { if (req.method !== 'GET' || req.url !== '/') return next(); // ... });With multiple handlers for the same route:
app.get('/', authorize('ADMIN'), function (req, res) { // ... });vs.
const authorizeAdmin = authorize('ADMIN'); app.use('/', function (req, res, next) { if (req.method !== 'GET' || req.url !== '/') return next(); authorizeAdmin(req, res, function (err) { if (err) return next(err); // ... }); });With parameters:
app.get('/item/:id', function (req, res) { let id = req.params.id; // ... });vs.
const pathToRegExp = require('path-to-regexp'); function prepareParams(matches, pathKeys, previousParams) { var params = previousParams || {}; // TODO: support repeating keys... matches.slice(1).forEach(function (segment, index) { let { name } = pathKeys[index]; params[name] = segment; }); return params; } const itemIdKeys = []; const itemIdPattern = pathToRegExp('/item/:id', itemIdKeys); app.use('/', function (req, res, next) { if (req.method !== 'GET') return next(); var urlMatch = itemIdPattern.exec(req.url); if (!urlMatch) return next(); if (itemIdKeys && itemIdKeys.length) req.params = prepareParams(urlMatch, itemIdKeys, req.params); let id = req.params.id; // ... });
Note: Express' implementation of these features are contained in its
Router,Layer, andRoute.From Stack Overflow: asked by Andre Vorobyov, answered by Jonathan Lonowski (CC BY-SA 4.0)
What is the difference between res.end() and res.send()?
First of all,
res.send()andres.end()are different.res.send()will send the HTTP response. Its syntax is,res.send([body])The body parameter can be a Buffer object, a String, an object, or an Array. For example:
res.send(new Buffer('whoop')); res.send({ some: 'json' }); res.send('<p>some html</p>'); res.status(404).send('Sorry, we cannot find that!'); res.status(500).send({ error: 'something blew up' });See this for more info.
res.end()will end the response process. This method actually comes from Node core, specifically theresponse.end()method ofhttp.ServerResponse. It is used to quickly end the response without any data. For example:res.end(); res.status(404).end();Read this for more info.
From Stack Overflow: asked by sudheeshcm, answered by itzmebibin (CC BY-SA 4.0)
Writing to files in Node.js
There are a lot of details in the File System API. The most common way is:
const fs = require('fs'); fs.writeFile("/tmp/test", "Hey there!", function(err) { if(err) { return console.log(err); } console.log("The file was saved!"); }); // Or fs.writeFileSync('/tmp/test-sync', 'Hey there!');From Stack Overflow: asked by Gjorgji, answered by Brian McKenna (CC BY-SA 4.0)
How to get GET (query string) variables in Express.js on Node.js?
In Express it's already done for you and you can simply use req.query for that:
var id = req.query.id; // $_GET["id"]Otherwise, in NodeJS, you can access req.url and the builtin
urlmodule to url.parse it manually:var url = require('url'); var url_parts = url.parse(request.url, true); var query = url_parts.query;From Stack Overflow: asked by XMen, answered by Marcus Granström (CC BY-SA 4.0)
How to access POST form fields in Express?
Things have changed once again starting Express 4.16.0, you can now use
express.json()andexpress.urlencoded()just like in Express 3.0.This was different starting Express 4.0 to 4.15:
$ npm install --save body-parserand then:
var bodyParser = require('body-parser') app.use( bodyParser.json() ); // to support JSON-encoded bodies app.use(bodyParser.urlencoded({ // to support URL-encoded bodies extended: true }));The rest is like in Express 3.0:
Firstly you need to add some middleware to parse the post data of the body.
Add one or both of the following lines of code:
app.use(express.json()); // to support JSON-encoded bodies app.use(express.urlencoded()); // to support URL-encoded bodiesThen, in your handler, use the
req.bodyobject:// assuming POST: name=foo&color=red <-- URL encoding // // or POST: {"name":"foo","color":"red"} <-- JSON encoding app.post('/test-page', function(req, res) { var name = req.body.name, color = req.body.color; // ... });Note that the use of
express.bodyParser()is not recommended.app.use(express.bodyParser());...is equivalent to:
app.use(express.json()); app.use(express.urlencoded()); app.use(express.multipart());Security concerns exist with
express.multipart(), and so it is better to explicitly add support for the specific encoding type(s) you require. If you do need multipart encoding (to support uploading files for example) then you should read this.From Stack Overflow: asked by murvinlai, answered by Drew Noakes (CC BY-SA 4.0)
How to access the GET parameters after "?" in Express?
So, after checking out the express reference, I found that
req.query.colorwould return me the value I'm looking for.req.params refers to items with a ':' in the URL and req.query refers to items associated with the '?'
Example:
GET /something?color1=red&color2=blueThen in express, the handler:
app.get('/something', (req, res) => { req.query.color1 === 'red' // true req.query.color2 === 'blue' // true })From Stack Overflow: asked by Hanfei Sun, answered by Hanfei Sun (CC BY-SA 4.0)
Related topics
Where these questions come from
Open-source collections on GitHub, official documentation, a government careers service and the Stack Exchange sites, each used under its own licence. The answers are the authors' own words: we only tidy the layout, leave out pictures, and cut a long answer with a link to the rest. Stack Exchange answers stay under CC BY-SA and name who asked and who answered.
- Stack Overflowby its contributors, named on each answerCC BY-SA16 questions