在ExpressJS中创建工作表单

时间:2015-01-28 02:11:20

标签: javascript node.js forms express

我是NodeJS和ExpressJS开发的新手(一周左右)。我正在尝试使用ExpressJS框架在NodeJS中创建一个Web应用程序。我要做的其中一件事就是为我的应用程序构建一个注册表单。我已经使用npm安装了body-parser中间件来读取表单数据。

我使用HoganJS作为我的模板框架。我的视图文件夹中有一个名为register.hjs的页面。此页面有一个表单

<form method="post">
    <input type="text" name="name">
    <input type="text" name="age">
    <input type="submit">
</form>

我正在努力解决这两个问题:

  1. 如何阅读.js
  2. 中的表单值
  3. 提交表单后如何将用户重定向到其他页面。
  4. 这就是我想要做的事情(尽管可能不正确)。

    在我的app.js

    //get
    app.get('/register', routes.register);
    
    //post
    app.post('/welcome', routes.welcome);
    

    在我的index.js

     /* GET about page.*/
     exports.register = function(req, res) {
       res.render('register');
      };
    
    /*POST registered user*/
    
    exports.welcome = function(req, res) {
    
    // pull the form variables off the request body
    var name = req.body.name;
    var age = req.body.age;
    
    //just to make sure the information was read
    console.log(name);
    console.log(age);
    
    res.render('welcome');
    
    };
    

    我很确定我错过了一些原因,因为当我运行我的服务器时,它会出错:

    错误:Route.get()需要回调函数但得到[object Undefined]

    我做错了什么?是否有任何优雅的方式来读取表单数据并将用户重定向到不同的页面?

    感谢。

    ---------------------------更新------------------- ---------

    以下是app.js代码的其余部分

       var express = require('express');
       var path = require('path');
       var favicon = require('serve-favicon');
       var logger = require('morgan');
       var cookieParser = require('cookie-parser');
       var bodyParser = require('body-parser');
    
      //routes to the pages
      var routes = require('./routes/index');
      var users = require('./routes/users');
      var register = require('./routes/register');
    
      var app = express();
    
     // view engine setup
     app.set('views', path.join(__dirname, 'views')); //app.set('the name of your    view folder', )
     app.set('view engine', 'hjs');
    
    //get
    app.get('/register', routes.register);
    
    //post
    app.post('/welcome', routes.welcome);
    
    // uncomment after placing your favicon in /public
    //app.use(favicon(__dirname + '/public/favicon.ico'));
    app.use(logger('dev'));
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({ extended: false }));
    app.use(cookieParser());
    app.use(express.static(path.join(__dirname, 'public')));
    
    app.use('/', routes);
    app.use('/users', users);
    app.use('/register', register);
    
    //error handlers 
    //error handlers
    
     module.exports = app;
    

2 个答案:

答案 0 :(得分:1)

为了简单理解表达的表达方式如何理解这段代码: 在理解了这段代码后,使用路由器和其他正文解析器配置---

var express = require('express');

/*
 * body-parser is a piece of express middleware that 
 *   reads a form's input and stores it as a javascript
 *   object accessible through `req.body` 
 *
 * 'body-parser' must be installed (via `npm install --save body-parser`)
 * For more info see: https://github.com/expressjs/body-parser
 */
var bodyParser = require('body-parser');

// create our app
var app = express();

// instruct the app to use the `bodyParser()` middleware for all routes
app.use(bodyParser());

// A browser's default method is 'GET', so this
// is the route that express uses when we visit
// our site initially.
app.get('/', function(req, res){
  // The form's action is '/' and its method is 'POST',
  // so the `app.post('/', ...` route will receive the
  // result of our form
  var html = '<form action="/" method="post">' +
               'Enter your name:' +
               '<input type="text" name="userName" placeholder="..." />' +
               '<br>' +
               '<button type="submit">Submit</button>' +
            '</form>';

  res.send(html);
});

// This route receives the posted form.
// As explained above, usage of 'body-parser' means
// that `req.body` will be filled in with the form elements
app.post('/', function(req, res){
  var userName = req.body.userName;
  var html = 'Hello: ' + userName + '.<br>' +
             '<a href="/">Try again.</a>';
  res.send(html);
});

app.listen(80);

答案 1 :(得分:0)

app.js:

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var routes = require('./routes/index');

var app = express();

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

// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);

module.exports = app;

index.js:

var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/register', function(req, res) {
  res.render('register');
});

router.post('/welcome', function(req, res) {
    console.log(req.body.name);
    console.log(req.body.age);
});



module.exports = router;