首页 > 解决方案 > 如何在 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 

});



标签: javascriptnode.jsexpress

解决方案


您可以使用 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) => {
   ...
});

推荐阅读