Home > Software engineering >  How node js parameter works?
How node js parameter works?

Time:09-19

I have seen these code in my project.

when 2 parameters:

app.use("*", (req: Request, res: Response) => {
});

when 3 parameters:

app.use("*", (req: Request, res: Response, next: NextFunction) => {
});

when 4 parameters:

app.use("*", (err: any, req: Request, res: Response, next: NextFunction) => {
});

Q1) Is there any documentation on why we use err as the first param? I'm pretty confused with this approach. How many types of arguments are there!?

Q2) I need to add a header in all responses. To be more precise I need to add CSP in the response header. Should I add using a middleware approach i.e., app.use(csp); Or any suggestions.

CodePudding user response:

Question 1:

Three parameters function is actual Express Middleware, which contains

req : Request Object, res: Response Object, next: Next Function

next() function is used to transfer the current flow to next middleware. For Example, let's say we have two middlewares.

app.use((req, res, next) => {
    console.log('THis is first Middleware')
    req.nextMiddlewareValue = 'Previous Middleware value'
    /* Code flow will transfer to the next middleware, defined below */
    next()
})

app.use((req, res, next) => {
  // If we try to console te req.nextMiddlewareValue object
  console.log(req.nextMiddlewareValue)    // Previous Middleware value
})

Make sure both middlewares should be used next to another.

Four parameters function middleware, basically, an error middleware which is provided by the ExpressJS. ExpressJS Error Handling

For, 4 parameters middleware, the first arg is for error, Let's use the above example again

app.use((req, res, next) => {
  /* Do Some Stuff */
  /* Now, instead of changing values, we will pass an error to next function */
  next(new Error('Error Occured in this middleware!'))
  /* Now this error will reach 4 Args middleware, known as error middleware */
})


app.use((err, req, res, next) => {
  /* This middleware handles all errors that will be passed to next() function in any middleware */
  /* Let's console err here */
  console.log(err.message) // Error Occurred in this middleware!
})

Make sure to use error middleware to end of all middlewares.

Question 2:

If you want to set any header for res object you can use like this

app.use((req, res, next) => {
  /* Set Header to res object */
  res.set({
    'Content-Type': 'text/plain',
    'Content-Length': '123',
    'ETag': '12345'
  })

  /* and call next function, now this res object will pass to all middlewares after it.*/
  next()
})

Make sure to use this middleware above all middlewares, so you can access it in any middleware, This will set it as global headers for all middlewares

There are multiple ways to set headers in ExpressJS. Follow this answer to know more.

I hope this will help you to understand Express Middlewares.

  • Related