不能POST表单node.js - express

时间:2013-02-15 20:35:40

标签: node.js express

使用express 3.1.0我有一个超级简单的形式:

<form action="/signup" method="post">
    <div>
        <label>Username:</label>
        <input type="text" name="username"/><br/>
    </div>
    <div>
        <label>Password:</label>
        <input type="password" name="password"/>
    </div>
    <div><input type="submit" value="Sign Up"/></div>
</form>

并在app.js中:

/**
 * Module dependencies.
 */

var express = require('express')
  , routes = require('./routes')
  , fs = require('fs')
  , User = require('./models/User.js')
  , user = require('./routes/user')
  , http = require('http')
  , path = require('path');

var app = express();

app.configure(function(){
  app.set('port', process.env.PORT || 3000);
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.use(express.favicon());
  app.use(express.logger('dev'));
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(app.router);
  app.use(express.static(path.join(__dirname, 'public')));
});

app.configure('development', function(){
  app.use(express.errorHandler());
});

app.get('/', routes.index);
app.get('/form', function(req, res) {
    fs.readFile('./form.html', function(error, content) {
        if (error) {
            res.writeHead(500);
            res.end();
        }
        else {
            res.writeHead(200, { 'Content-Type': 'text/html' });
            res.end(content, 'utf-8');
        }
    });
});

app.post('/signup', function(req, res) {

    var username = req.body.username;
    var password = req.body.password;
    User.addUser(username, password, function(err, user) {
        if (err) throw err;
        res.redirect('/form');
    });
});

app.get('/users', user.list);


http.createServer(app).listen(app.get('port'), function(){
  console.log("Express server listening on port " + app.get('port'));
});

当试图发布这个表格时,我得到了:

Cannot POST /signup

并在控制台中:

"NetworkError: 404 Not Found - http://localhost:3000/signup"

我在这里缺少什么?

3 个答案:

答案 0 :(得分:27)

你的例子适合我。我删除了对用户,用户和路由的引用,以便我可以运行它,并在控制台中正确接收和显示HTTP POST。

app.post('/signup', function(req, res) {
    var username = req.body.username;
    var password = req.body.password;
    console.log("post received: %s %s", username, password);
});

我怀疑错误在你的User.addUser()代码中。

答案 1 :(得分:6)

router.route('/signup')

    // (accessed at POST http://localhost:3000/api/signup)
    .post(function(req, res) {
        var username = req.body.username;
        var password = req.body.password;
        res.json(
            { 
               message: 'signup success',
                username : username,
                 password : password,
            }
        );
    })
    .get(function(req,res){
        res.json({message: 'get request from signup'});
});

// REGISTER OUR ROUTES -------------------------------
// all of our routes will be prefixed with /api
app.use('/api', router);

答案 2 :(得分:-4)

你可以这样写:

action="http://localhost:3000/sin"