javascript - 如何在 Express 中将价值从一条路线传递到另一条路线?
问题描述
我有一个简单的路由,它发出一个 POST 请求并返回一个具有多个值的对象。我想在另一个(不同的)路由中使用一个返回值来实现不同的逻辑。有没有办法将此类数据从一条路线传递到另一条路线?
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
});
解决方案
您可以使用 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
});
或者,您可以在路线上使用中间件
IE
router.post('/register', middleware(), (req, res) => {
...
});
//定义中间件
function middleware(){
return function(req, res, next){
...perform actions
next()
}
}
//重用路由中的中间件
router.post('/verify', middleware(), (req, res) => {
...
});
推荐阅读
- vue.js - vue - 将子组件代码移动到另一个文件
- java - 我可以从 Swing Mouse Adapter/Listener 方法获取数据吗?
- php - 枢轴模型中的调用关系
- firebase - 在 Firebase 存储上启用 CORS 以进行 localhost 测试
- javascript - RXJS 通过属性“id”组合/合并两个 Observable 数组
- java - Selenium:如果选择标签包含样式=“显示:无;”,如何从下拉列表中选择选项
- javascript - Lightning 组件,在控制器中检索查找记录值
- python - 如何将此 Python2.x 代码转换为 Python3.x?
- reactjs - 当光标在 React JS 中的组件上快速移动时如何管理状态值?
- sql - 从所有项目相互引用的交叉引用表中获取唯一行