大家好,我尝试使用表单和文本输入来制作页面,并尝试在另一侧取值并收到错误“无法发布”。这是我的代码,非常感谢。 为什么它不起作用? 大家好,我尝试使用表单和文本输入来制作页面,并尝试在另一侧取值并收到错误“无法发布”。这是我的代码,非常感谢。 为什么它不起作用?
这是 app.js
var express = require('express');
var app = express();
var home = require('./home');
var user = require('./user');
var mongodb=require('./mongodb');
app.use(express.static(__dirname + '/public'));
//listen port 3000
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
//start ejs package
app.set('view engine', 'ejs');
//use the help.js and user.js
app.use('/', home);
app.use('/user', user);
app.use('/mongo',mongodb);
这是 mongodb.js:
var express = require('express');
var router = express.Router();
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
var app = express();
var bodyparser=require('body-parser');
let obj = null;
app.use(bodyparser.urlencoded({extended:true}));
app.use(bodyparser.json());
app.set('view engine', 'ejs');
getDfroMongo();
function getDfroMongo(){
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("mydb");
//Sort the result by name:
var sort = { car : 1 };
dbo.collection("customers").find().sort(sort).toArray(function(err, result) {
if (err) throw err;
console.log(result);
obj = result;
db.close();
});
});
}
app.post('/',function(req,res){
//var myid = {ObjectId:req.body.id};
var customername = req.body.customername;
// var age = req.body.age;
// var myimg = req.body.img;
// obj = {CustomerName: customername, Age: age, img: myimg };
//res.send(htmlData);
console.log(customername);
});
app.get('/', function(req, res){
res.render(__dirname + '/views/mongodbview',{result:obj}); //if html file is root directory
});
module.exports = app;
module.exports = router;
mongodbview.ejs:
<html>
<head>
<link href="/css/style.css" rel="stylesheet" type="text/css">
<%include title%>
</head>
<body>
<form class="form" action="/" method="post" name="regForm">
<div class="form-group">
<input type="text" name="customername" class="form-control" id="customername" placeholder="customername">
</div>
<div class="form-group">
<input type="text" name="age" class="form-control" id="age" placeholder="age">
</div>
<div class="form-group">
<input type="text" name="img" class="form-control" id="img" placeholder="img">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
<table>
<tr>
<th>Car</th>
<th>Model</th>
<th>Year</th>
<th>image</th>
</tr><br>
<% for(let i=0; i < result.length; i++) { %>
<tr>
<td><%= result[i].Car%></td>
<td><%= result[i].Model%></td>
<td><%= result[i].Year%></td>
<td> <img src="\images\<%= result[i].img%> "width="80" height="80"></td><br>
</tr>
<% } %>
</table>
</body>
</html>
谢谢大家的精彩网站!
答案 0 :(得分:0)
您已经在post handler函数中注释了res.send。结果,没有响应发送到客户端。
由于没有足够的回复而将其发布为答案而不是评论