为什么我的ExpressJS服务器不接受POST请求?

时间:2011-09-13 01:05:51

标签: post node.js express

var express = require('express');

var app = module.exports = express.createServer();

// Configuration

app.configure(function(){
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(express.compiler({ src: __dirname + '/public', enable: ['less'] }));
  app.use(app.router);
  app.use(express.static(__dirname + '/public'));
});

// Routes

app.get('/*', function(req, res){
  console.log(req.headers);
  res.end();
});

app.listen(1234);

当我在浏览器中加载http://localhost:1234时,它按预期工作,我得到以下输出:

{ host: 'localhost:1234',
  'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:6.0.2) Gecko/20100101 Firefox/6.0.2',
  accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
  'accept-language': 'en-us,en;q=0.5',
  'accept-encoding': 'gzip, deflate',
  'accept-charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
  connection: 'keep-alive' }

但是当我发布数据时,它不会返回任何内容。知道为什么吗?

2 个答案:

答案 0 :(得分:6)

您正在使用app.get。这只会响应GET次请求。您可能想看看app.post是否有效。

答案 1 :(得分:1)

如果你想要一条捕获路线:

app.all('*', function(req, res){
  res.send(200, req.route.method+' '+req.originalUrl);
});

请记住,您调用app.method(route...)的顺序很重要。如果您将该catchall路由放在路由代码的顶部,它将匹配每个请求。由于它总是发送响应,因此不会执行任何进一步向下的匹配路由。

如果要跳过特定路由功能并继续任何后续匹配路由,可以在路由功能中传递和调用next回调:

app.all('*', function(req, res, next){
  console.log(req.route.method+' '+req.originalUrl);
  next();
});

app.get('/', function(req, res){
  res.send(500);
});

app.post('/', function(req, res){
  res.send(404);
});
相关问题