请放心,我几个月前才开始编码。
如何从匹配路由中的 placeOrder 路由访问变量?
//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 })
});
};
我想将 currentPrice 变量传递给此路由=>
//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)
好吧,你有两个主要选择:
// 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();
});
};
// 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 });
});
};
请小心,使用第二种方法,您的路线将能够访问
req.locals.currentPrice
内部的该变量,但只有在访问 placeOrder 路线之后,否则它将是未定义的。
希望有帮助
编辑:它没有正式记录,但您可以访问
req.locals
和 res.locals
,通常需要使用它,因为如果您使用模板渲染器(例如 ejs),它将使用 res.locals 和它可能会导致竞争条件
距离提出问题和上次回复已经过去两年多了,所以我希望这不会违反社区的任何准则。然而,这可能仍然可以帮助任何其他与我有同样问题的人,他们在遇到这个线程寻找相同的解决方案后必须弄清楚它。
除了@eroironico给出的第一个选项以及作为对第二个选项的修正之外,创建“locals”对象并将其附加到路线路径的“res”对象将使其属性在整个生命周期内可用应用程序。
例如; 如果您在 placeOrder 路由上创建 res.locals.currentPrice = data.c,则可以在应用程序的整个生命周期中使用 res.locals.currentPrice 访问 locals 对象的 currentPrice 属性.
但是如果你在 req 对象上这样做,你将会遇到一个未定义的错误,与首先提出这个问题的 @calin125 观察到的一样。
//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 })
});
};