在节点应用程序

时间:2017-07-30 14:59:23

标签: javascript json node.js

问题/问题

当我发布表单数据时我的req.body未定义...这很奇怪,因为我有多个其他页面的表单,我以相同的方式发布数据但突然间我得到了这个问题而且我做了不知道为什么。这似乎是一个常见的问题,但我找不到适合我的修复程序。

到目前为止我尝试了什么......

代码

<form action="/changePassword" method="post" onsubmit="event.stopPropagation(); return passwordChange(this);" enctype="application/x-www-form-urlencoded" novalidate="">
    <input id="password1" placeholder="password" name="password1" maxlength="30" class="form-control input-sm chat-input" type="password">
    <input id="password2" placeholder="confirm password" name="password2" maxlength="30" class="form-control input-sm chat-input" type="password">
    <input id="changePassword" value="Change Password" type="submit">
</form>

app.post('/ changePassword',users.changePassword);

module.exports.changePassword = function(req, res){
    console.log(req.is('json')); // false and req.body is undefined
    ...
    ...        
    res.redirect('/'); 
});

如果需要其他代码,请告诉我。

编辑:不确定这是否值得一提,但我还有其他问题,这些问题再次与其他网页无关。当我尝试验证密码时,return false;不会阻止页面发布/执行。我必须包含event.stopPropagation()

附加代码:

./仓/万维网

!/ usr / bin / env node

/**
 * Module dependencies.
 */

var app = require('../app');
var debug = require('debug')('app:server');
var http = require('http');
var express= require('express');

/**
 * Get port from environment and store in Express.
 */

var port = parseInt(process.env.PORT, 10) || 3000;

app.set('port', port);

/**
 * Create HTTP server.
 */

// var server = http.createServer(app);

//var server = app;

/**
 * Listen on provided port, on all network interfaces.
 */

app.use((err, req, res, next) => {
  console.log(err.stack || err.message);
  if (res.headersSent)
    return next(err)
  res.status(500).send('Internal Server Error')
})

app.listen(port);
app.on('error', onError);
app.on('listening', onListening);

/**
 * Event listener for HTTP server "error" event.
 */

function onError(error) {
  if (error.syscall !== 'listen') {
    throw error;
  }

  // handle specific listen errors with friendly messages
  switch (error.code) {
    case 'EACCES':
      console.error('Port ' + port + ' requires elevated privileges');
      process.exit(1);
      break;
    case 'EADDRINUSE':
      console.error('Port ' + port + ' is already in use');
      process.exit(1);
      break;
    default:
      throw error;
  }
}

/**
 * Event listener for HTTP server "listening" event.
 */

function onListening() {
  debug('Listening on port ' + server.address().port);
}

app.js

/*jslint node:true */
/*global $, jQuery, alert*/
"use strict";
var express = require('express');
var path = require('path');
var fs = require('fs');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var expressSession = require('express-session');
var mongoose = require('mongoose');
var mongoStore = require('connect-mongo/es5')({ session: expressSession });
var passport = require('passport');
var debug = require('debug')('app:server');
var uriUtil = require('mongodb-uri');
var mongodb = require('mongodb');
var MongoClient = mongodb.MongoClient;

var assert = require('assert');


mongoose.Promise = global.Promise;

var MONGOLAB_URI = ****;
var mongooseUri = uriUtil.formatMongoose(MONGOLAB_URI);
var mongoConnection = mongoose.connect(MONGOLAB_URI, function (err, db) {
    if (err) {
        console.log('Unable to connect to MongoDB: ', err);

    } else {
        console.log('Connection has been established...');        
    }
});

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}))


app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

console.log("__dirname: " + __dirname);

app.use(expressSession({
    secret: 'RCNEfyBUAcHnPeQxFWyBTr',
    cookie: { maxAge: 60*60*1000 },
    resave: true,
    saveUninitialized: true
}));


app.use(passport.initialize());
app.use(passport.session());

require('./routes/index')(app, conn);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});

module.exports = app;
exports.mongoConnection = mongoConnection;

index.js

module.exports = function (app, conn) {
    ... 

    app.post('/signup', users.signup);
    app.post('/login', users.login)
    app.post('/changePassword', users.changePassword);                         
    app.post('/password', users.password); // send new password
    app.post('/user/create_test', users.create_test);
    app.post('/user/calculatesubjects', users.calculate_subjects);
    app.post('/user/calculatetopics', users.calculate_topics);
    app.post('/test/:username/:testid/:noq/:quesnum', users.answer_selected);

    // Admin posts
    app.post('/admin/update_subjects_topics', admin.update_subjects_topics);
    app.post('/admin/add_question', admin.add_question);
}

密码更改功能

function passwordChange(form) 
{
    if(form.password1.value != "" && form.password1.value == form.password2.value) {
      if(form.password1.value.length < 6) {
        alert("Error: Password must contain at least six characters!");
        form.password1.focus();
        return false;
      }

      re = /[a-z]/;
      if(!re.test(form.password1.value)) {
        alert("Error: password must contain at least one lowercase letter (a-z)!");
        form.password2.focus();
        return false;
      }
    } else {
      alert("Error: Please check that you've entered and confirmed your password!");
      form.password2.focus();
      return false;
    }

    return true;
}

1 个答案:

答案 0 :(得分:0)

听起来问题是表单没有以JSON格式发送。默认情况下,html表单以urlencoded(您指定的)发送。除非您通过javascript发送表单并指定json,否则您应该使用bodyParser.urlencoded

var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded());

我很困惑其他类似的形式是如何工作的。如果您使用类似jQuery的东西通过脚本发送它们(而不是使用原生html),表单仍然可以通过json发送。