我是nodejs的新手并且一般表达。我试图使用body-parser从html页面获取POST值。我尝试了几个建议,但无法让它对我有用。
这是代码。任何指针都将受到高度赞赏。提前致谢。
Server.js
var express = require('express');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var Subscribe = require('./models/subscribe');
mongoose.connect('CREDENTIALS');
var app = express();
app.use(bodyParser.json(), bodyParser.urlencoded({ extended: false }));
var port = 3000;
var router = express.Router();
router.get('/', function(req, res) {
res.json({ message: 'Test...' });
});
var subscribeRoute = router.route('/subscribe');
subscribeRoute.post(function(req, res) {
var subscribe = new Subscribe();
subscribe.email = req.body.email_notify;
console.log(subscribe);
subscribe.save(function(err) {
if (err)
res.status(500).send(err);
res.status(200);
});
});
app.use('/api', router);
app.listen(port);
的index.html
<form action="http://localhost:3000/api/subscribe/" method="POST" enctype="application/json">
<input type="text" onfocus="if (this.value=='E-mail Address') this.value = ''" onblur="if (this.value=='') this.value = 'E-mail Address'" value="E-mail Address" id="email_notify" name="email_notify" />
<button id="notify_me" ontouchstart="">Notify Me!</button><br/>
</form>
由于 Sujith
答案 0 :(得分:-1)
制作<input type='submit'>
而不是<button>
并从表单中删除enctype
。
此外,在Chrome中打开开发人员工具,网络标签,并检查请求是否已发送到您的服务器
答案 1 :(得分:-1)
更改此
app.use(bodyParser.json(), bodyParser.urlencoded({ extended: false }));
到此
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));