req.body没有填充表单数据

时间:2015-06-04 18:31:06

标签: javascript node.js express

以下文件是我尝试向我的nodejs(express)服务器提交POST请求。 req.body不会填充表单中的任何类型的数据。我做了很多搜索,发现许多针对这个特殊问题的解决方案包括在我的路线前移动bodyparser,并确保在表单字段中包含一个名称。
任何帮助表示赞赏。

app.js

[variables]
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(validator({errorFormatter: -----}));
[other middleware]
require('./passport')(app, passport);
require('./routes')(app, passport);
[start server]

index.jade

block content
h1= title
p Please register below
.error-messages
    ul.errors
        if errors
            each error, i in errors
                li.alert.alert-danger #{error.msg}
form(method='post', action='/signup', enctype='multipart/form-data')
    .form-group
        label Name
        input.form-control(type='text', name='name', placeholder='Enter name')
    .form-group
        label Email
        input.form-control(type='email', name='email', placeholder='Enter email')
    .form-group
        label Username
        input.form-control(type='text', name='username', placeholder='Enter a username')
    .form-group
        label Password
        input.form-control(type='password', name='password')
    .form-group
        label Confirm Password
        input.form-control(type='password', name='passwordConfirm')
    input.btn.btn-primary.pull-right(type='submit', name='submit', value='Sign Up')

index.js (从app.post调用('/ signup',...)

var name = req.body.name,
    email = req.body.email,
    username = req.body.username,
    password = req.body.password,
    passwordConfirm = req.body.passwordConfirm;

name = 'meg';

console.log('name: ' + req.body.name);
console.log('email: ' + req.body.email);
console.log('name2: ' + name);
console.log(req.body);
console.log(req.headers);
console.log(req.is('json'));

console.log

name: undefined
email: undefined
name2: meg
{}
 { host: 'xx.xx.xx.xxx:xx',
 connection: 'keep-alive',
  'content-length': '623',
  'cache-control': 'max-age=0',
   accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
  origin: 'http://xx.xx.xx.xxx:xxxx',
  'user-agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36      (KHTML, like Gecko) Chrome/42.0.2311.152 Safari/537.36 OPR/29.0.1795.60',
   'content-type': 'multipart/form-data; boundary=----     WebKitFormBoundaryYJyUQjMbfAn9Cr64',
  dnt: '1',
  referer: 'http://xx.xx.xx.xxx:xxxx/signup',
  'accept-encoding': 'gzip, deflate, lzma',
  'accept-language': 'en-US,en;q=0.8',
  cookie: 'connect.sid=s%3Au9o1F_i22gHj0ZCqpHQiKWDLBGOVU1MJ.6DdtQAqbR6sriI8zF3AjQy6y1TDMD93TMGI7fRIJ5mM' }
 false

2 个答案:

答案 0 :(得分:5)

您为表单使用了错误的enctype,默认情况下表示不支持multipart(用于文件上传),您需要使用x-www-form-urlencoded。

form(method='post', action='/signup', enctype='application/x-www-form-urlencoded')

答案 1 :(得分:3)

您正在发送multipart/form-data请求,但您未使用multipart/form-data兼容正文解析中间件。处理该格式的一些示例中间件模块是multermultiparty / formidable