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

Viewed 182

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)
1 Answers

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

Related