[英]How to pass value from one route to another in Express?
I have a simple route that makes a POST request and returns an object with a number of values.我有一个简单的路由,它发出一个 POST 请求并返回一个具有多个值的对象。 I want to use one of the returned values in another (different) route for different logic.
我想将另一个(不同)路由中的返回值之一用于不同的逻辑。 Is there a way to pass such data from one route to another?
有没有办法将这些数据从一条路线传递到另一条路线?
router.post('/register', (req, res, next) => {
// call some function that returns an object for use in another route eg:
myFunction()
.then((data) => {
console.log(data)
})
.catch((err) => {
console.log(err)
})
});
router.post('/verify', (req, res, next) => {
// use the data returned from the register route for verification logic
});
You can use npm package connect-flash for passing data between routes您可以使用 npm package connect-flash在路由之间传递数据
var express = require('express');
var flash = require('connect-flash');
var app = express();
app.use(flash());
app.get('/login', function(req, res){
// Set a flash message by passing the key, followed by the value, to req.flash().
req.flash('username', 'Gaurav Gupta')
res.redirect('/profile');
});
app.get('/profile', function(req, res){
// Get an array of flash messages by passing the key to req.flash()
let message = req.flash('username')
res.render('index', { message: message }); // or {message} only es6 feature
});
Or alternatively you can use middlewares on the routes或者,您可以在路由上使用中间件
ie IE
router.post('/register', middleware(), (req, res) => {
...
});
//define middleware //定义中间件
function middleware(){
return function(req, res, next){
...perform actions
next()
}
}
//reuse middleware in route //在路由中重用中间件
router.post('/verify', middleware(), (req, res) => {
...
});
You can try express-session to store the value in the session then read it from session variable.您可以尝试 express-session 将值存储在会话中,然后从会话变量中读取它。 or you can create an encrypted token and send it to the user as register response, then in verify the route take the token and decrypt it.
或者您可以创建一个加密的令牌并将其作为注册响应发送给用户,然后在验证路由时获取令牌并对其进行解密。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.