0

POST リクエストをリッスンするように Express を構成する方法に関する他のいくつかの質問を読みましたが、サーバーに送信する単純な POST クエリを出力しようとすると、空の JSON または未定義が継続的に取得されます。

私はこれを設定しています:

//routes
require('./routes/signup.js')(app);

// Configuration
app.configure(function(){
    app.use(connect.bodyParser());
    app.use(express.methodOverride());
    app.register(".html", hulk);
    app.set('views', __dirname + '/views');
    app.set('view options', {layout: false});
    app.set('view engine', 'hulk');
    app.use(express.static(__dirname + '/public'));
    app.use(app.router);
});

次に、routes/signup.js次のようになります。

var common_functions = require('../common_functions.js');
var views            = require('../views/view_functions.js');
var globals          = require('../globals.js');
var mongoose         = require('mongoose');

//declare classes
var User = mongoose.model('User');

module.exports = function(app){
    /**
     * SignUp GET
     */
    app.get('/signup', function(req, res){
        res.render('signup/signup.html');
    });

   /**
    * SignUp POST
    */
   app.post('/signup', function(req, res){
    console.log(JSON.stringify(req.body));
    console.log(req.body);
    res.send(JSON.stringify(req.body));
});

}

テンプレートは次のようになります。

{{> header.html }}
{{> navigation.html }}
{{> body.html }}
<form action="/signup" method="post">
    <input name="email"/>
    <input type="submit"/>
</form>
{{> footer.html }}

どのパーシャルにも特に興味深いものはありません。

2 つconsole.logは undefined を出力しますが、res.send()は以前と同じ html を返すだけです。ここで何が間違っていますか?

4

1 に答える 1

1

Expressは、ルーターの動詞関数のいずれかへの最初の呼び出しで、ルーターミドルウェアを自動マウントします(まだマウントされていない場合)。したがって、configブロックの上のルートにロードすることにより、ルーターミドルウェアはスタック内の最初のミドルウェア(bodyParserの上)になります。ルートファイルのロードをconfigureブロックの下に移動すると、この問題が修正されます。

Express.jsドキュメントの構成セクションから:

Note the use of app.router, which can (optionally) be used to mount the application routes, otherwise the first call to app.get(), app.post(), etc will mount the routes.

http://expressjs.com/guide.html#configuration

于 2012-07-09T15:59:01.917 に答える