What is the function signature of app.render, how is app.render used in the Next.js example files? - express

I have a Next.js app with an Express server in server.js (using custom server deployment.)
In the Next.js example server.js file, app.render(req, res, '/a', req.query); is used.
I understand that res.render uses app.render and that app.render is used for serving 'raw' content by means other than the HTTP protocol.
The Express docs detail that app.render takes the arguments:
app.render(view, [locals], callback)
So in the the Next.js example files, app.render(req, res, '/a', req.query);
req=view,
res=locals,
'/a'=locals,
req.query=callback
I'm struggling to make sense of the use of app.render here, and the arguments passed to it.
What are the arguments passed here, and how do they correlate with the documented express function signature?
As a supplementary question -
Next.js docs define this pattern as: This is obviously a non-standard routing strategy.
In what way is it non-standard, and why not use a standard routing pattern for example purposes?

Related

How to inject a request (bypass HTTP protocol stack) in nodejs express?

Imagine this sample Express app straight from the documentation:
const express = require('express')
const app = express()
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.listen(3000)
What is the idiomatic way to invoke the '/' endpoint programmatically from a different point in the same application code? Assume that I already removed the last line app.listen(3000).
The reason for this is that I want to take something like express-pouchdb and write an adapter for a different wire protocol, but leveraging the extensive routes already defined. I want to invoke these routes directly from js code without going over the network.
The application has dozens of routes already defined so changing each one to direct function calls as suggested in the first comment is not an option.
UPDATE:
I tried calling app.route.dispatch() but nothing comes back on the rsp object.
Your question is a duplicate of this answer: Is it possible to call Express Router directly from code with a "fake" request?
You can use run-middleware module exactly for that. You create an express app a usual, and then you can call the app using your parameters

difference between app.use('/users', usersRouter); and require(./routes/users)(app)?

In the express tutorial from mozilla,
https://developer.mozilla.org/en-US/docs/Learn/Server-side/Express_Nodejs/skeleton_website
they write
var usersRouter = require('./routes/users');
app.use('/users', usersRouter);
In other tutorials, they write something like this,
require('./routes/authRoutes')(app);
Are the two pretty much equivalent?
Without seeing the code for the other tutorials that you mentioned I cannot be sure exactly how they consume the app object that is passed to the imported code, but I suspect that whatever code is implemented in the .routes/authRoutes module simply connects a router object to the specified app object. This would most likely be done in the same way as the code that you provided from the Mozilla Express tutorial.
In both cases, a route handler is being defined and then registered as a handler for any routes that match the specified route. In the case that you mentioned that route would be the /users route. So the usersRouter object would have a number of route handlers defined, for example, for routes /abc and /def. So registering the usersRouter object as a route handler for the /users route would mean that the routes /users/abc and /users/def would be handled.

Adding property to the request using Node and Express

I have a MEAN application, and I'm handling authentication using passport. What I want to do is exactly what happens to the user on the passport, which can be accessed from the request like req.user. I have not found any solutions to reach that result. Can you give me any advice?
You can add properties to the request or response objects by creating a middleware and using it in your app. E.g.
// Defining middleware
function myMiddleware(req, res, next) {
req.myField = 12;
next();
}
// Using it in an app for all routes (you can replace * with any route you want)
app.use('*', myMiddleware)
Now all your request objects in your handlers will have myField property.
To add extra properties to the request and response object you need to extend the response and request interface.
index.d.ts files are used to provide typescript type information about a module that’s written in JavaScript.For express, the index.d.ts is present inside the #types/express folder inside the node_modules folder.
Use this link-
https://dev.to/kwabenberko/extend-express-s-request-object-with-typescript-declaration-merging-1nn5

Unobtrusive middle-ware for Expres.js to inspect request body

Does there exist a thirdparty middleware or a way to create such middleware for Express.js that allows for intercepting all requests and inspecting the request's body content without affecting subsequent middleware such as bodyParser or route endpoints which may rely on the raw body such as express-http-proxy?
From what I can tell bodyParser itself seems to work in a somewhat obtrusive way that does not allow a route to override the default parsing behavior. The express documentation describes how request.body is filled in by middleware such as bodyParser. This behavior of bodyParser makes sense from simplicity and performance perspective but doesn't make it a great candidate for creating middleware which needs to inspect the contents of a request and let the remaining portion of the app working without modification. This is especially true seeing that depending on the parsing middleware the results may be in entirely different formats. After some digging I'm left wondering if it's generally possible to pull this off with express or perhaps once you read the request body you eliminate the ability to make use of further middleware such as bodyParser or express-http-proxy which expect to access the body directly.
Possibly related:
express req.pipe() does not work
You could always use the raw-body package with express middleware like so:
var getRawBody = require('raw-body');
var typer = require('media-typer');
app.use(function (req, res, next) {
getRawBody(req, {
length: req.headers['content-length'],
limit: '1mb',
encoding: typer.parse(req.headers['content-type']).parameters.charset
}, function (err, string) {
if (err) return next(err)
req.text = string
next()
})
})
If your only concern is performance, I wouldn't worry too much about body-parser as it's unlikely to have a massive performance impact. If you can, I'd suggest you just use body-parser with a typical express middleware app.use(..) to inspect the request body.

Can I use multiparty for a single route in my express app?

I have an Express 3 app that uses bodyParser for most routes. (Most routes only accept multipart.) I have a single route that is going to be parsing files up to 1GB in size which bodyParser can't seem to handle. I would like to use multiparty for only this route so I don't have to rewrite the whole API. Is this possible?
You can supply middleware to a single route by doing this:
var multipartyMiddleware = function (req,res,next){
//put your code to parse multipart here and call "next" when done
}
app.post('/this/is/a/single/route', multipartyMiddleware, function(req,res){
//do normal business logic in this route and send the response
})
If you need to bypass the multipart parsing in the old bodyParser in express 3 you can replace this:
app.use(express.bodyParser())
with this:
app.use(express.json())
app.use(express.urlencoded())
This works because the source of the bodyParser middleware reveals that it is just a combo of three middleware parsers: multipart, json, and urlencoded.
see the connect 2.X source here: https://github.com/senchalabs/connect/blob/2.x/lib/middleware/bodyParser.js#L54