解析NodeJS

时间:2016-08-13 09:13:27

标签: javascript node.js post pug body-parser

我正在尝试解析表单帖子上的select(下拉)框元素。

请求正文仅包含'txt1'元素。没有'lstSelect'元素的迹象。

我知道我应该使用身体解析器,但不知道如何以及哪一个?

这是Jade模板:

 extends layout
    block content
    .jumbotron
        h1 Calculator
        form(action='/calc',method='post', id="tableForm" )
            p
            select(name="lstSelect", id="lstSelect", size ="5")
            option(value='one') One
            option(value='two') Two
            option(value='three') Three
            p
            input(type='text', name='txt1', id='txt1') 
            p  
            input(type='submit' name='StdDev', value='StdDev') 

这是NodeJS文件:

//"use strict";
var express = require('express');
var routes = require('./routes/index');
var api = require('./routes/api/index');
var http = require('http');
var path = require('path');
var app = express();
var bodyParser = require('body-parser');
var multiparty = require('multiparty');
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(require('stylus').middleware(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));

app.post('/calc', function (req, res) {
    var lstSelect = req.body.lstSelect; <- undefined
    var form = new multiparty.Form();
    form.parse(req, function (err, fields, files) {
        // fields fields fields
        var x = 1; <- bp never reached
    });
    var b = req.body; <- only txt1 element is here
});
编辑:大缺陷。选择的值在request.body但我仍然需要整个列表。我需要选择框值的数组。

1 个答案:

答案 0 :(得分:0)

select没有任何option元素,因此在提交时会跳过它。以下应该解决它;

extends layout

block content
    .jumbotron
        h1 Calculator
        form(action='/calc', method='post', id='tableForm')
            p
                select(name='lstSelect', id='lstSelect', size='5')
                    option(value='one') One
                    option(value='two') Two
                    option(value='three') Three
            p
                input(type='text', name='txt1', id='txt1') 
            p  
                input(type='submit' name='StdDev', value='StdDev') 

还修复了一些缩进,因此您的输入元素位于段落内。