我正在尝试使用node.js和ejs模板将从输入中获取的值发布到同一页面。该模板可用于传递页面标题,但是当我尝试传递从输入中获取的值时,它将无法正常工作。它说“字幕”数组未定义。这让我有些困惑。你能帮我吗?
app.js
const express = require('express');
const parser = require('body-parser');
const path = require('path');
const app = express();
app.use(parser.urlencoded({ extended: false }));
app.use(parser.json());
app.use((req, res, next) => {
res.locals.userValue = null;
next();
})
app.set('view engine', 'ejs');
app.set('views', 'views');
app.get('/', (req, res, next) => {
res.render('index', {
topicHead: 'Subtitles Page',
});
console.log('Home Page!');
})
app.post('/subtitle/add', (req, res, next) => {
let subtitles = [];
sub_title: req.body.subtitleInput
subtitles.push(sub_title)
console.log(subtitles);
res.render('index', {
subtitles,
topicHead: 'Subtitles Page'
});
});
app.listen(3000, () => {
console.log('Server running on port 3000')
})
index.ejs
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<main>
<h1><%= topicHead %></h1>
<form name="form1" method="POST" action="/subtitle/add">
<table>
<tr>
<td>Subtitle</td>
<td><input type="text" name="subtitleInput"></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Save"></td>
</tr>
</table>
</form>
<% for (let sub of subtitles) { %>
<h1><%= sub %></h1>
<% } %>
</main>
</body>
</html>
我得到的错误;
ReferenceError: D:\code\getSub\views\index.ejs:25
23| </table>
24| </form>
>> 25| <% for (let sub of subtitles) { %>
26| <h1><%= sub %></h1>
27| <% } %>
28| </main>
subtitles is not defined
at eval (eval at compile (D:\code\getSub\node_modules\ejs\lib\ejs.js:633:12), <anonymous>:14:24)
at returnedFn (D:\code\getSub\node_modules\ejs\lib\ejs.js:668:17)
at tryHandleCache (D:\code\getSub\node_modules\ejs\lib\ejs.js:254:36)
at View.exports.renderFile [as engine] (D:\code\getSub\node_modules\ejs\lib\ejs.js:485:10)
at View.render (D:\code\getSub\node_modules\express\lib\view.js:135:8)
at tryRender (D:\code\getSub\node_modules\express\lib\application.js:640:10)
at Function.render (D:\code\getSub\node_modules\express\lib\application.js:592:3)
at ServerResponse.render (D:\code\getSub\node_modules\express\lib\response.js:1012:7)
at D:\code\getSub\app.js:18:9
at Layer.handle [as handle_request] (D:\code\getSub\node_modules\express\lib\router\layer.js:95:5)
答案 0 :(得分:2)
此行sub_title: req.body.subtitleInput
中存在问题。
也许您想要这样的let sub_title = req.body.subtitleInput;
来保留值。
无论如何,您都不需要它,您可以像这样直接推送输入值。
let subtitles = [];
subtitles.push(req.body.subtitleInput)
console.log(subtitles);
res.render('index', {
subtitles,
topicHead: 'Subtitles Page'
});
此外,由于使用相同的ejs文件,您还必须检查subtitles
是否未定义。
<% if (locals.subtitles){ %>
<% subtitles.forEach(function (sub) { %>
<h1><%= sub %></h1>
<% }) %>
<% } %>