node.js&快递 - 无法发布表单数据

时间:2014-11-13 03:41:55

标签: javascript node.js forms mongodb form-submit

大部分时间都在为此工作 - 早上...... 我有一个大型表格,在整个宪法文件的各个阶段收集评论。最后 - 用户提交表单,表单重定向到/ const-comments(它应该!),这是一个POST路由。最终呈现的页面显示了注释(实际上将保存到MongoDB,但我还没有那么远。

所以表格的基础是

<form class="form-horizontal" id="constitutionForm" action="../routes/constitution-comments" method="post" >
    <fieldset>
        <div class="form-group">
            <label class="control-label" for="GENERALComments">Your Comments</label>
                <div class="col-md-12">                     
                    <textarea class="form-control" id="GENERALComments" name="GENERALComments"></textarea>
                </div>
        </div>
    </fieldset>
<button class="btn btn-info" type="submit">Submit</button>
</form>

路线如下:

module.exports = function(server){

    server.post('/constitution', function(req, res){        
        res.render('./views/constitution/comments.ejs', {
            GENERALComments: req.body.GENERALComments,
        });
        // THIS IS NOT DISPLAYED
        console.log("\tIn /constitution POST");
    });
}

路线末端的console.log没有出现,所以看来我没有来这里!

呈现(或不呈现)的视图如下所示:

<div class="container">
  <div class="row">
    <div class="col-lg-12 center ">
        <h1 class="text-shad">
            Your Draft Constitution Comments
        </h1>
    </div>
    <div>
        <%= GENERALComments %>
    </div>
</div>

我的路线和观点的排列方式如下: routes

可以在此处找到完整的应用程序: [到目前为止完全应用] [2]

为清楚起见:服务器是快递app.js

如何将表单数据发送到POST?

更新:完整代码

server.js

console.log("Adding Requires");
var express = require('express');
var fs = require('fs');
var path = require('path');
var urlEncoded = require('urlencoded-request-parser');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var override = require('method-override');
var rest = require('node-restful');

console.log("Creating Server Object");
var server = express();
server.locals.moment = require('moment');
server.set('ServerVersion', "5.0.1.7");

console.log("Server setting port");
var port = process.env.port || 1337;

console.log("Server setting \'Require Models\'");
var modelsPath="./models/"; 
fs.readdirSync(modelsPath).forEach(function(file) {
    var models=modelsPath+file;
    var bfile = path.basename(file,'.js');
    console.log("\tAdding model: " + bfile)
    require(models)(server);
});


console.log("Connecting to MongooseDB");
mongoose.connect("mongodb://mvm-mongodb.cloudapp.net/ccslabs-main");

var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function callback () {
  console.log('Connected to MongoDB successfully');
});


server.use('/constitution', function(req, res, next) {
  console.log('Request URL:', req.originalUrl);
  next();
}, function (req, res, next) {
  console.log('Request Type:', req.method);
  next();
});

server.use('/constitution-comments', function(req, res, next) {
  console.log('Request URL:', req.originalUrl);
  next();
}, function (req, res, next) {
  console.log('Request Type:', req.method);
  console.log('Request Body:', req.body )
  console.log('Request Content-Type: ', req.get('Content-Type'));
  next();
});

server.use('/comments', function(req, res, next) {
  console.log('Request URL:', req.originalUrl);
  next();
}, function (req, res, next) {
  console.log('Request Type:', req.method);
  next();
});

server.disable('x-powered-by');

console.log("Server setting \'Server.Uses\'");
server.use(urlEncoded());
server.use(bodyParser.urlencoded({extended: true}));
server.use(bodyParser.json());
server.use(override());

// this middleware will be executed for every request to the app
// server.use(function (req, res, next) {
//  console.log('Time: %s : Req: %s', server.locals.moment(),req.ip );
//  next();
// })

console.log("Server setting \'Require Routes\'");
var routePath="./routes/"; 
fs.readdirSync(routePath).forEach(function(file) {
    var route=routePath+file;
    var models=modelsPath+file;
    var bfile = path.basename(file,'.js');
    console.log("\tAdding route: " + bfile)
    require(route)(server);
});

console.log("\tAdding Static Files\' routes");
server.use(express.static(__dirname + "/content"));

console.log("Server creating \'Server.Sets\'");
server.set('view engine', 'ejs');
server.set('views', __dirname);
server.set('Content-Type','application:json')
// Why does the version not display??
server.set('ver',"0.0.2.8")
console.log("Server Version: "+ server.ver);

server.listen(port);
console.log("Server listening on port " + port);

完整代码可在此处找到:Github link (temporary)

2 个答案:

答案 0 :(得分:0)

action上的<form>不正确。它应该是(假设server是您的Express app而不是已安装的路由器):action="/constitution"

答案 1 :(得分:0)

解决

以上问题的解决方案如下:

1)我在Action和路径文件中将路径更改回“/ post-put”。 2)我在表单中添加了enctype =“multipart / form-data”。

所以表单现在看起来像

<form method="post" action="/post-put" enctype="multipart/form-data"> 
    <fieldset>

        <!-- Form Name -->
        <legend>Which Test Type</legend>

        <!-- Multiple Radios (inline) -->
        <div class="form-group">
            <label class="col-md-2 control-label" for="TestType">Please test our</label>
            <div class="col-md-4"> 
                <label class="radio-inline" for="TestType-0">
                    <input type="radio" name="TestType" id="TestType-0" value="SoftwareTest" checked="checked">
                    Software
                </label> 
                <label class="radio-inline" for="TestType-1">
                    <input type="radio" name="TestType" id="TestType-1" value="HardwareTest">
                    Hardware
                </label>
            </div>
        </div>
    </fieldset>
    <input type='submit' class="btn btn-default" id='submit' value='Submit your Test'/>
</form>

替代解决方案

将表单输入保持为enctype="application/x-www-form-urlencoded"在App.js(我的server.js)中删除app.use(bodyparser.urlencoded());app.use(bodyParser.urlencoded({extended: true}));更改为app.use(bodyParser.urlencoded());

现在表单的POST方法有效!感谢那些试图提供帮助的人。