我创建了表单并尝试从服务器数据中获取数据,因为我在我的节点应用程序中使用了 ejs 模板。没有显示错误,但我无法在控制台中获取数据。
下面是我的代码:
server.js
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));
app.set('views',path.join(__dirname,'views'));
app.set('view engine','ejs');
const port = process.env.PORT || 3000;
const key = process.env.SECRET_KEY;
app.get('/register',(req,res) => {
res.render('register',{title:'Register here'});
});
app.post('/register',(req,res) => {
const name=req.body;
console.log(name);
});
app.listen(port,(req,res) => {
console.log(`App is running at ${port}`);
});
register.ejs
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous">
<title><%= title %></title>
<style>
h1 {
text-align: center;
margin-top:50px;
}
.form{
margin-top:50px;
margin-left:30%;
margin-right:30%;
}
button{
margin-top:20px;
}
</style>
</head>
<body class="container">
<h1><%= title %></h1>
<div class="form">
<form action='/register' method='POST'>
<input name="nam" class="form-control" type="text" placeholder="Name" aria-label="default input example">
<button type="button" class="btn btn-primary">SUBMIT</button>
</form>
</div>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js" integrity="sha384-IQsoLXl5PILFhosVNubq5LC7Qb9DXgDA9i+tQ8Zj3iwWAwPtgFTxbJ8NT4GN1R8p" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/js/bootstrap.min.js" integrity="sha384-Atwg2Pkwv9vp0ygtn1JAojH0nYbwNJLPhwyoVbhoPwBhjQPR5VtM2+xf0Uwh9KtT" crossorigin="anonymous"></script>
</body>
</html>
有人让我知道我在上面的代码中做错了什么或需要正确的地方。
答案 0 :(得分:1)
在 Nodejs post 请求中使用它:
<button type="submit">
并更改此:
Some
答案 1 :(得分:1)
要提交表单,您必须告诉按钮提交表单。使用 <button type="submit" class="btn btn-primary">SUBMIT</button>
不会提交您的表单,而只是充当被点击的按钮。
要解决此问题,只需执行以下操作:
db.Set<TEntity>()
点击按钮时,不会提交当前所在的表单!