繁体   English   中英

Express和Body-Parser不返回值

[英]Express and Body-Parser not returning values

我是nodejs的新手,总体上表示出来。 我正在尝试使用body-parser从html页面获取POST值。 我尝试遵循SO中的一些建议,但是无法使其对我有用。

这是代码。 任何指针将不胜感激。 提前致谢。

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>

谢谢苏吉思

使<input type='submit'>代替<button>并从表单中删除enctype

同样在Chrome中打开开发人员工具的“网络”标签,然后检查请求是否已发送到您的服务器

改变这个

app.use(bodyParser.json(), bodyParser.urlencoded({ extended: false }));

对此

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM