让我们假设我有这条路线
app.post('/category',function(req,res){
res.redirect('/category/item');
})
用户将在此路线中发布一些数据,然后将自动重定向到另一条路线以获取示例/category/item
以发布其他数据
所以最后我希望将这两个帖子的数据收集在路由/category
中,另一个收集在路由/category/item
中以查询我的数据库。
答案 0 :(得分:1)
使用express session是保存第一个发布数据然后在第二个请求中获取这些数据的最佳选择,这是一个示例:
添加会话中间件
const express = require('express'),
app = express(),
session = require('express-session');
// use session middleware
app.use(session({
secret: 'secret',
resave: false,
saveUninitialized: true,
cookie: { maxAge: 60000 }
}));
在会话中存储数据
app.post('/category', function (req, res) {
// store posted data in the session
req.session.category = req.body;
res.redirect('/category/item');
});
app.post('/category/item', function (req, res) {
// force users to deal with /category first
if ( !req.session.category ) {
return res.redirect('/category');
}
// get data from the session
var category = req.session.category;
// req.body contains the second submited data
});
答案 1 :(得分:1)
您可以使用http
状态代码307
来执行此操作,这表示应使用相同的方法重复请求并发布数据。
app.post('/', function(req, res) {
res.redirect(307, '/category/item');
});
这将保留发送数据。
作为参考,307 http代码规范是:
307临时重定向(自HTTP / 1.1起)在这种情况下,请求 应该使用另一个URI重复,但未来的请求仍然可以使用 原始URI.2与303相比,请求方法不应该 重新发出原始请求时更改。例如,一个POST 必须使用另一个POST请求重复请求。
答案 2 :(得分:0)
您需要将第一次调用的数据存储在内存(变量)或数据库中。 HTTP是一种完全无状态的协议,因此无法跨越该边界进行通信(一个请求到另一个边界)。我建议将数据存储在数据库中,可能存放在临时保存表中,然后在第二次请求后将其同步。
app.post('/category',function(req, res){
// store data from req.body in a temporary table in your DB
// be sure to key it with something that will tie it to future requests
// such as a userId, sessionId, etc
res.redirect('/category/item');
});
app.post('/category/item',function(req, res){
// find existing data from the temporary DB table using some key
// like the userId, sessionId, etc
// then add take the new data from req.body, merge it with the data
// from the temporary table above, and store it in the final
// location in the DB
});