calin125
calin125

Reputation: 11

How to pass a variable from one Express route to another.?

Please go ease, I've only started coding a couple of months ago.

How can I access a variable from the placeOrder route in the match route?

//Get Price//
const placeOrder = (req, res) => {
var symbol = req.query.symbolID.split(" - ")[0].toUpperCase()
console.log(symbol)
finnhubClient.quote(symbol, (error, data, response) => {
   const currentPrice = data.c
    console.log(currentPrice)
    res.send({ currentPrice })
 });

};

I want to pass the currentPrice variable to the this route =>

//Match orders 
const match = async(req, res) => {

// I want to access the currentPrice variable here //


const { orderType, orderTimeFrameInput, tradeAmount, symbolSearch, kofTimeInput } = 
 req.body

console.log(req.body.symbolSearch)
const orders = await knex("orderbook_table")
.where({ order_type: "Call" })
.where({ market: symbolSearch })
.select()

console.log(orders)

Upvotes: 1

Views: 1303

Answers (2)

It's been more than two years since the question and the last response so I am hoping this will not violate any of the community's guidelines. This might however still serve to help any other person with the same issue as me who had to figure it out after bumping into this thread looking for the same solution.

In addition to the first option as given by @eroironico and as an amendment to his second option, creating and attaching a 'locals' object to the 'res' object of a route path will make its properties available through out the lifetime of application.

For example; if you create res.locals.currentPrice = data.c on the placeOrder route, you can have access to the currentPrice property of the locals object throughout the lifetime of the application using res.locals.currentPrice.

But if you do that on the req object you will have an undefined error, same as observe by @calin125 who asked the question in the first place.

//full code snippet//
//Get Price//
const placeOrder = (req, res) => {
    var symbol = req.query.symbolID.split(" - ")[0].toUpperCase()
    console.log(symbol)
    finnhubClient.quote(symbol, (error, data, response) => {
        const currentPrice = data.c
        console.log(currentPrice)
        //Now all your routes can access this variable
        //Even up to the global error middleware if defined
        res.locals.currentPrice = currentPrice
        res.send({ currentPrice })
     });
};

Upvotes: 0

eroironico
eroironico

Reputation: 1372

Ok you have two main options:

  • If your routes come one after the other (for example: /placeorder > /match) you can attach the variable on the request:
// Added 'next' parameter
const placeOrder = (req, res, next) => {
    const symbol = req.query.symbolID.split(" - ")[0].toUpperCase()
    console.log(symbol)
    finnhubClient.quote(symbol, (error, data, response) => {
        const currentPrice = data.c;
        console.log(currentPrice);
        req.currentPrice = currentPrice;
        // By calling next you will navigate to the next route and the request object will have your variable
        next();
    });
};
  • If your routes are completely separated (which i guess is your case) you can use the local property:
// Don't need to use next anymore, you can evend send a response
const placeOrder = (req, res) => {
    const symbol = req.query.symbolID.split(" - ")[0].toUpperCase()
    console.log(symbol)
    finnhubClient.quote(symbol, (error, data, response) => {
        const currentPrice = data.c;
        console.log(currentPrice);
        // Now all of your routes can access this variable
        req.locals.currentPrice = currentPrice;
        res.send({ currentPrice });
    });
};

Be carefull tho, with the second approach your routes will be able to access that variable inside req.locals.currentPrice but only after the placeOrder route has been accessed, otherwise it will be undefined.

Hope it helped

EDIT: It's not officially documented but you'll be able to access both req.locals and res.locals, generally req it's used because if you're using a template renderer(ejs for example) it will use the res.locals and it can cause race conditions

Upvotes: 1

Related Questions