如何在Express中的路线之间传递数据 [英] How to Pass Data Between Routes in Express
问题描述
假设我有一条POST
路由,它接收一些数据.
Suppose I have this POST
route which receives some data.
app.post('/getData', function(req, res){
var retrievedData = req.body.exampleVariable;
// Send data to GET method
});
我有这个GET
方法可以呈现页面,但是需要我在POST
方法中检索到的数据
And I have this GET
method which renders a page, but needs the data I retrieved in the POST
method
app.get('/displayData', function(req, res){
// Retrieve data from POST method and display it.
res.render('/examplePage.ejs', {retrievedData : req.retrievedData});
});
将retrievedData
变量从给定的POST
路由传递到GET
路由的最佳方法是什么?
What is the best way to pass the retrievedData
variable from the given POST
route to the GET
route?
请注意,res.render()
方法似乎仅在app.get()
类型方法中起作用
As a side note, the res.render()
method only seems to work in app.get()
type methods
推荐答案
您可以使用
app.post('/getData', function(req, res){
app.set('data', req.body.exampleVariable);
});
app.get('/displayData', function(req, res) {
res.render('/examplePage.ejs', {retrievedData : app.get('data')});
});
,但是不能保证返回的数据将是用户设置的数据,并且直到用户提出获取路由的请求之前,数据都不会被发送.这也使您的Express Server处于有状态状态,这有很多可能的缺点.
but there is no guarantee that the returned data will be the data that the user set, and the data won't be sent until a user makes a request to get route. This is also making your express server stateful, which comes with a lot of possible disadvantages.
您可以在此处
如果您希望应用程序是无状态的,则可以将其传递到外部某个地方,例如独立于express服务器的mysql之类的远程服务器.
If you want your app to be stateless, you can instead pass your to somewhere external, like a remote server like mysql which is independant of the express server.
如果有任何用处,您也可以根据需要在同一请求中发送和接收数据,就像您的评论中所说的那样. 如果您有类似下面的内容,那么只要您肯定对"/data"发出"POST"请求,就可以正常工作,考虑到它对于"GET"请求也可以正常工作.
In case it is of any use, you can also send and receive data in the same request if you prefer, as in your comment this seems to be what you are trying to do. If you have something like below, it should be working fine, as long as you are definitely making a "POST" request to "/data", considering it was working fine for "GET" requests.
app.post('/data', function(req, res){
res.render('/examplePage.ejs', {
retrievedData: req.body.exampleVariable
});
});
下面是一个示例快递应用程序,用于演示它可能如何工作
Below is an example express app to show how this might work
form(method="post" action="data")
input(type="text" name="data" value="some data")
input(type="submit" value="submit")
data.jade
h1=data
server.js
require('express')()
.use(require('body-parser').urlencoded({ extended: false }))
.get('/form', (req, res) => res.render('form.jade'))
.post('/data', (req, res) => res.render('data.jade', { data: req.body.data }))
.listen(8083);
如果启动服务器并转到"localhost:8083/form", 提交表单后,您将看到一个呈现页面,其中包含您发布的数据.
If you start the server and go to "localhost:8083/form", after submitting the form you are shown a rendered page containing the data that you posted.
这篇关于如何在Express中的路线之间传递数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!