【发布时间】:2020-10-20 13:45:49
【问题描述】:
我只是在学习 express,我尝试在 localhost:3000 上创建一个简单的网页。我创建了一个带有提交按钮的文本框,单击该按钮将获取文本框中的文本元素并将其打印在控制台上。
我的 node.js 代码是:
const express = require('express')
const path = require('path')
const hbs = require('hbs')
const app=express();
app.set('view engine', 'hbs');
const dir= path.join(__dirname,'../templates/views');
const partials=path.join(__dirname,'../templates/partials')
app.set('views',dir);
hbs.registerPartials(partials);
app.get('', (req, res) => {
res.render('test')
});
app.listen(3000, () => {
console.log(`Server started on port`);
});
test.hbs文件代码为:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
{{>header}}
<form class="form">
<input type="text" placeholder="Write here" class="textbox">
<input type="submit" class="btn">
</form>
<script src="./test.js"></script>
</body>
</html>
而javascript代码是
const values={
nodeForm:document.querySelector('.form'),
nodeText:document.querySelector('.textbox'),
nodeBtn:document.querySelector('.btn')
}
values.nodeForm.addEventListener('submit',e=>{
e.preventDefault();
console.log(nodeText.value)
})
但是当我打开localhost:3000时,控制台页面给我一个错误,说GET http://localhost:3000/test.js net::ERR_ABORTED 404 (Not Found)
编辑:如果我将脚本放在 test.hbs 文件中的脚本标记中,Javascript 可以正常工作
【问题讨论】:
-
querySelector('.forms')class="forms"在哪里?为什么属性中有逗号?placeholder="Write here",class="textbox" -
@epascarello,我改了。它没有用。不过谢谢。
标签: javascript node.js express handlebars.js