Shamoon
Shamoon

Reputation: 43491

Why won't my ExpressJS server accept POST requests?

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);

When I load http://localhost:1234 in a browser, it works as expected and I Get the following output:

{ 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' }

But when I post data, it doesn't return anything. Any idea why?

Upvotes: 0

Views: 1200

Answers (2)

Plato
Plato

Reputation: 11052

If you want a catchall route:

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

Remember that the order you invoke app.method(route...) matters. If you put that catchall route at the top of your routing code, it will match every single request. Since it always sends a response, any matching routes further down won't be executed.

If you want to skip a particular routing function and continue to any subsequent matching routes, you can pass and invoke a next callback in the routing function:

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);
});

Upvotes: 1

icktoofay
icktoofay

Reputation: 128993

You're using app.get. That will only respond to GET requests. You might want to see if app.post works.

Upvotes: 6

Related Questions