Search code examples
node.jsexpressserverroutesmiddleware

Passing JSON data in Express Middleware


I have the following route in my express app:

 app.post("/users/me/trackers/court_cases", caseValidator, DriversController.court_cases);

I would like to be able to pass information from my second middleware, caseValidator, to the third set of middleware. The second middleware currently fetches JSON data from a RESTful API, that I would like to pass along to the final route before sending it to the user.

Here's my current case validator function:

caseValidator = function(req, res, next){
    var case_id = req.body.case_id;

    var authOptions = {
        method: 'GET',
        url: `https://www.courtlistener.com/api/rest/v3/dockets/${case_id}/`,
        headers: {
            'Authorization' : "myauth"
        },
        json: true
    };

    var url = `https://www.courtlistener.com/api/rest/v3/dockets/${case_id}/`
    axios(authOptions)
        .then((response) => {
            console.log("success!")
            next();

            //// Pass in the JSON data to the next middleware?
        })
        .catch((error) => {
            res.status(400)
               .send(error)
        });
};

Solution

  • you can use req.someVar.

    axios(authOptions)
       .then(response => {
            console.log("success!");
            req.someVar = response.data;
            next();
       })
    

    then in next middleware you have access to that data.