【发布时间】:2019-02-05 02:18:33
【问题描述】:
我正在尝试从我的主站点获取输入。提交输入后,页面应重定向到/view。似乎它成功重定向到/view(因为console.log() 被触发,但res.render 不起作用。如果我手动转到/view 它正在呈现页面。
这是我的app.js文件的代码:
// load the things we need
var express = require('express');
var app = express();
let bodyParser = require("body-parser");
let article = '';
//Set the view engine to ejs
app.set('view engine', 'ejs');
app.use('/static', express.static('static'))
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json())
//Index page
app.get('/', function (req, res) {
res.render('index')
});
//Get the input from the form
app.post('/searcharticle', function (req, res) {
article = req.body.article;
res.redirect('/view')
return article;
});
//Page to output the input
app.get('/view', function (req, res) {
console.log(article)
res.render('view', {
article: article
})
})
app.listen(8080);
console.log('Server on 8080');
这是我的 folder structure
感谢您的帮助!
【问题讨论】:
-
有什么错误吗?
-
没有没有错误输出@mehta-rohan
-
需要查看您的文件夹结构
-
我将文件夹结构添加到问题@mehta-rohan
-
无关:您的代码中有竞争条件,因为您在全局范围内存储了
article。请求特定数据不属于全局范围。例如,您可以将req.body.article存储在会话、文件系统或数据库中。或者直接在你的 POST 处理程序中直接res.render(也不需要从它返回任何东西,因为返回值被丢弃)
标签: javascript node.js express ejs