我有一个文件 server.js,如下所示:
var express = require('express');
var app = express();
var mongoose = require('mongoose');
var Bear = require('./models/bear');
mongoose.connect('mongodb://123:pass123@ds1383.mlab.com:53/bears');
var bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({extended : false}));
app.use(bodyParser.json());
var port = 8080;
var router = express.Router();
router.use(function(req, res, next){
//console.log("Working....");
next();
});
router.get('/', function (req, res){
res.json({ message: "API Works!"});
});
router.route('/bears')
.post(function(req, res) {
console.log("hi");
var bear = new Bear(req.body); // create a new instance of the Bear model
console.log(bear);
// save the bear and check for errors
bear.save(function(err) {
if (err)
return res.send(err);
res.json({ message: 'Bear created!' });
});
});
app.use("/", (req, res) =>{
res.sendFile(__dirname + "/index.html");
});
app.use('/books', router);
app.listen(port);
console.log("Listening on port "+ port);
我的 Index.html 文件如下所示:
<head>
</head>
<body>
<form method="POST" action="/bears">
Enter Book to add
<input type="text" id="book_name"/>
<br /><br />
Enter Quantity
<input type="number" id="book_quantity"/>
<br /><br />
Enter Price
<input type="text" id="book_price"/>
<br /><br />
<button type="submit"> Add Book </button>
</form>
</body>
我想知道为什么它不进入
router.route('/bears')
.post(function(req, res){});
当点击“添加图书”按钮时,我什至认为我已经设置了
action="/bears"
属性。
当使用curl进行测试时,它工作得很好,只是不能使用这个html表单
我像这样使用curl进行测试:
curl -i -X POST -H "Content-Type: application/json"-d '{ "book_name": "Android", "book_quantity": 2,"book_price": 580 }' 本地主机: 8080/册
我是 Javascript 新手,因此我们将不胜感激!
最佳答案
对于通过 html 表单进行的 post 调用,所有输入标签的“name”属性都是必需的
<form method="POST" action="/books/bears">
Enter Book to add
<input type="text" id="book_name" name="book_name"/>
<br /><br />
Enter Quantity
<input type="number" id="book_quantity" name="book_quantity"/>
<br /><br />
Enter Price
<input type="text" id="book_price" name="book_price"/>
<br /><br />
<button type="submit"> Add Book </button>
</form>
也可以使用
app.use(bodyParser.urlencoded({ extended: true }));
在服务器代码中
这是因为form以application/x-www-form-urlencoded格式发送post数据,所以在服务器中以req.body.book_name访问。
如果需要json格式,则在客户端使用javascript并制作json然后发送。
关于javascript - 使用express.Router()时如何从HTML表单传递用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53235193/