重定向到在nodejs中传递响应数据的根url



通过传递一些用户详细信息重定向到主页url。下面的代码将重定向到根url,并通过url参数传递用户名。

exports.successfull = (req,res) => {
var userName = JSON.parse(req.body).username
res.redirect("/?username="+ userName);
}

因此客户端的预期url将是https://www.example.com/?username="John%20%Doe">

另一种方式是

res.send({
url: "/",
data: {
username: userName
}
})

res.send不会重定向,而是会发送字符串,这意味着在客户端它会给出"/"。

但是在url上不会有任何字符串参数。

因此,如果没有字符串params和使用重定向,我如何才能实现上述目标。如果我使用res.send,它将发送字符串,如果我使用res.redirect,我们需要附加params。

我只想重定向并传递数据,而不在url params 上显示用户名

我需要使用会话、cookie或其他什么吗?

您可能需要用不同的方式来思考这个问题。您可以在您的expressapp实例上调用一个setter,它将在app上设置一个变量,然后您可以稍后检索,但这将使您的web服务器有状态。如果你不知道自己在做什么,一个有状态的web服务器可能会非常bug。

相反,您可以在同一POST请求中接收数据并呈现模板。

app.post('/getdata', function(req, res){
res.render('/examplePage.SOMETEMPLATEENGINE', {
data: req.body.username
});
});

或者更好的是,您可以使用快速会话或Cookie。快速会话可以使用快速会话中间件来设置,并且可以这样设置

const session = require('express-session');
app.use(session({
name: "my-session-name",
secret: 'my-secret',
resave: false,
saveUninitialized: true,
store: // your prefered data store,
cookie: {
maxAge: oneDay
}
}));

这将需要使用CCD_ 3,因为会话将所有最终用户信息存储在数据库上。如果你想要一种更简单的方法,我认为你是一个初学者,你可以使用cookie解析器在cookie中实现数据。我建议你多看看那些文件。(别担心,它并不像看上去那么难(

一旦设置了cookie解析器中间件,cookie实现可能会是这样的。

app.post('/setdata', (req, res, next) => {
// we will set a cookie here
res.cookie('mycookie', {username: req.body.username})
// this will set a cookie on the clients browser with whatever value you wan't
})

现在,对于每个请求,客户端都会自动将此cookie发送到每个路由我们可以这样访问它。

// future route the user visits
app.get('/showcookie', (req, res, next) => {
// we can access the cookie we set if the user has visited the previous route like 
//this
let username = req.cookies.mycookie.username
// and you can do with it what you wan't afterward
})

如果你想要一个超级简单的快递应用程序,向你展示cookie的工作示例,这里有一个GitHub repo的链接,我写这个链接是为了向我的一些朋友展示cookie如何在快递中工作。我希望这能有所帮助。在转到其他事情之前,最好先了解您正在使用的内容,尤其是在处理用户数据时。干杯

最新更新