我正在使用express在node.js中制作一个web应用程序。这是对我所拥有的东西的简化:
var express = require('express');
var jade = require('jade');
var http = require("http");
var app = express();
var server = http.createServer(app);
app.get('/', function(req, res) {
// Prepare the context
res.render('home.jade', context);
});
app.post('/category', function(req, res) {
// Process the data received in req.body
res.redirect('/');
});
我的问题是:
如果我发现在/category中发送的数据不有效,我想向/页传递一些额外的上下文。我怎么能这样做呢?重定向似乎不允许任何类型的额外参数。
你可以通过查询字符串传递少量的键/值对数据:
res.redirect('/?error=denied');
主页上的javascript可以访问它并相应地调整它的行为。
注意,如果你不介意/category作为浏览器地址栏中的URL,你可以直接渲染而不是重定向。恕我直言,很多时候人们使用重定向,因为旧的web框架使直接响应变得困难,但表达起来很容易:
app.post('/category', function(req, res) {
// Process the data received in req.body
res.render('home.jade', {error: 'denied'});
});
@Dropped.on。Caprica评论说,使用AJAX消除了URL更改问题。
下面是我的建议,不使用任何其他依赖,只是节点和表达式,使用app.locals,这是一个例子:
app.get("/", function(req, res) {
var context = req.app.locals.specialContext;
req.app.locals.specialContext = null;
res.render("home.jade", context);
// or if you are using ejs
res.render("home", {context: context});
});
function middleware(req, res, next) {
req.app.locals.specialContext = * your context goes here *
res.redirect("/");
}
你可以通过查询字符串传递少量的键/值对数据:
res.redirect('/?error=denied');
主页上的javascript可以访问它并相应地调整它的行为。
注意,如果你不介意/category作为浏览器地址栏中的URL,你可以直接渲染而不是重定向。恕我直言,很多时候人们使用重定向,因为旧的web框架使直接响应变得困难,但表达起来很容易:
app.post('/category', function(req, res) {
// Process the data received in req.body
res.render('home.jade', {error: 'denied'});
});
@Dropped.on。Caprica评论说,使用AJAX消除了URL更改问题。
我们可以使用express-session发送所需的数据
当你初始化应用程序
const express = require('express');
const app = express();
const session = require('express-session');
app.use(session({secret: 'mySecret', resave: false, saveUninitialized: false}));
所以在重定向之前,只需要为会话保存上下文
app.post('/category', function(req, res) {
// add your context here
req.session.context ='your context here' ;
res.redirect('/');
});
现在您可以在会话的任何地方获取上下文。它可以通过request。session。context获得
app.get('/', function(req, res) {
// So prepare the context
var context=req.session.context;
res.render('home.jade', context);
});