【问题标题】:Express.js: node.js, express.js and jade in form post, doesn´t show the second pageExpress.js:表单帖子中的node.js、express.js和jade,不显示第二页
【发布时间】:2014-02-14 12:01:26
【问题描述】:

我是 node 和 express 的新手,我做了一个小应用程序,但它不起作用。我确实在第 1 页发帖,但应用程序没有显示第 2 页。结构和代码是:

/
/controller/controllers.js
/node_modules/express
             /jade
             /mongoose
/view/index1.jade
     /index2.jade
     /layout.jade
app.js
package.json

app.js

/* server */
var express = require('express')    
  , routes = require('./routes')
  , fs = require('fs');

//Create server
var app = express.createServer();

//Use controller
var controllers_path = __dirname + '/controllers'
    ,controller_files = fs.readdirSync(controllers_path);
    controller_files.forEach(function (file) {
        require(controllers_path+'/'+file)(app);
});

//Jade configuration
app.configure(function() {
    app.set('view options', { layout: false });
    app.use(express.static(__dirname + ''));
});

app.listen(3001);
console.log("listening on port %d", app.address().port);

controller.js

module.exports = function(app, auth){

    // Get
    app.get('/test1', function(req, res){
        res.render('index.jade', {});
    });

    // Post
    app.get('/test2', function(req, res){
        res.render('index2.jade', {});
    });

};

index.jade

extends layout
block content   
    form(method="post", action="/test2")
    p
    input(type="submit")

index2.jade

extends layout
block content
    p Page 2

layout.jade

h1 Test layout
block content

谢谢!

【问题讨论】:

  • 您没有处理帖子的路线...

标签: javascript jquery node.js express


【解决方案1】:

问题是您没有/test2 的POST 处理程序。在您的 HTML 中,您指定了 method="POST",但在您的控制器中,您仅处理 GET 方法。

你想把它改成这样:

// Post
app.post('/test2', function(req, res){
    res.render('index2.jade', {});
});

顺便说一句,如果你想处理所有的请求类型,可以使用app.all,然后根据方法类型决定做什么:

app.all('/test2', function(req, res){
    if(req.method==='GET'){
        // one response for GET requests
    } if(req.method==='POST'){
        // another response for POST requests
    } else {
        // catch all...PUT, DELETE, etc.
    }
});

【讨论】:

  • 我已经改变了它,当按下按钮时应用程序什么也不做。我在 app.post 中输入了一个日志......并通过控制台显示它。
  • 您是说 POST 处理程序的 console.log 在服务器上发生还是未发生?
  • 对不起,不显示日志,不进入 app.post('/test2', function(req, res)
  • 尝试在记录器中链接,看看发生了什么。 app.use(express.logger('dev'));
  • 它什么也没显示,你的意思是?它至少必须为/test1 记录一个GET,对吧?
猜你喜欢
  • 2011-08-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-12
  • 1970-01-01
  • 2018-12-31
  • 2020-10-13
相关资源
最近更新 更多