[英]export input query from one GET request and use them on separate requests
I am trying to use the input of the user on my RESTful API
in the query for one GET
request and use that data to randomize a number and use that info for the rest of the application.我正在尝试在我的
RESTful API
上使用用户的输入来查询一个GET
请求,并使用该数据随机化一个数字并将该信息用于应用程序的 rest。 any guidance about best solution to store the values and use them on different blocks throughout the application is appreciated.任何有关存储值并在整个应用程序的不同块上使用它们的最佳解决方案的指导都值得赞赏。 Part of the code sample is as below:
部分代码示例如下:
app.get("/start", (req, res) => {
const numberOfFigures = req.query.figures;
const randomBaseNumber = Math.random();
const theNumber = (randomBaseNumber * 10 ** numberOfFigures).toFixed(0);
res.send(`guess the ${numberOfFigures} digit number!`);
app.get("/guess", (req, res) => {
let guessedNumber = req.query.guess;
if (guessedNumber !== theNumber) {
console.log("Wrong! Guess again");
}
I am trying to use for instance theNumber value from /Start request in the /guess request!例如,我正在尝试在 /guess 请求中使用 /Start 请求中的 Number 值!
You need to keep theNumber
variable outside of the scope of both callbacks eg您需要将 Number 变量保留在两个回调的
theNumber
之外,例如
let theNumber = 0
app.get("/start", (req, res) => {
const numberOfFigures = req.query.figures;
const randomBaseNumber = Math.random();
theNumber = (randomBaseNumber * 10 ** numberOfFigures).toFixed(0);
res.send(`guess the ${numberOfFigures} digit number!`);
app.get("/guess", (req, res) => {
let guessedNumber = req.query.guess;
if (guessedNumber !== theNumber) {
console.log("Wrong! Guess again");
}
I would also use POST for the /guess
endpoint我也会将 POST 用于
/guess
端点
The following 3 ways of storing data come to mind:想到以下 3 种存储数据的方式:
Method 1 is the easiest way.方法1是最简单的方法。 The variable will be accessible from all the routes, and it will be erased if your app restarts.
该变量将可以从所有路由访问,并且如果您的应用重新启动,它将被删除。
let theNumber = 0;
...
app.get("/start", (req, res) => {
theNumber = ...
...
Methods 2 and 3 will make the variable, once created, persist even if the app restarts.方法 2 和 3 将使变量在创建后保持不变,即使应用程序重新启动也是如此。 However, for this simple use case, I'd say they're overkill.
但是,对于这个简单的用例,我会说它们是矫枉过正的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.