gpt4 book ai didi

node.js - Expressjs 中的链式请求

转载 作者:太空宇宙 更新时间:2023-11-04 02:50:52 25 4
gpt4 key购买 nike

我需要创建以下流程。我有两个端点,我需要将expressejs中第一个端点的结果传递到第二个端点。我想过做一些像指南所示的东西:

var cb0 = function (req, res, next) {
console.log('CB0');
next();
}

var cb1 = function (req, res, next) {
console.log('CB1');
next();
}

var cb2 = function (req, res) {
res.send('Hello from C!');
}

app.get('/example/c', [cb0, cb1, cb2]);

我应该如何将第一个函数产生的结果传递给第二个函数?

最佳答案

您需要创建新属性来请求参数,例如

var cb0 = function (req, res, next) {
// set data to be used in next middleware
req.forCB0 = "data you want to send";
console.log('CB0');
next();
}

var cb1 = function (req, res, next) {
// accessing data from cb0
var dataFromCB0 = req.forCB0

// set data to be used in next middleware
req.forCB1 = "data you want to send";
console.log('CB1');
next();
}

var cb2 = function (req, res) {
// accessing data from cb1
var dataFromCB2 = req.forCB1

// set data to be used in next middleware
req.forCB2 = "data you want to send";
res.send('Hello from C!');
}

app.get('/example/c', [cb0, cb1, cb2]);

关于node.js - Expressjs 中的链式请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31383718/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com