Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js express POST 404ing

I've got a small node.js application using the express framework, but for some reason I can't get my application to respond to POST requests. In the server log I simply get "POST / 404 5ms", and I can't figure out why.

EDIT: To clarify - My problem is that app.post doesn't seem to be doing anything

EDIT 2: I somehow managed to fix this last night, but now I can't figure out at what point i fixed it.

Node.js server code:

var express = require('express')
  , routes = require('./routes')
  , user = require('./routes/user')
  , http = require('http')
  , path = require('path');

var app = express();

// all environments
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(express.cookieParser('chocolatechip'));
app.use(express.session());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));


// development only
if ('development' == app.get('env')) {
  app.use(express.errorHandler());
}

//pages
//Landing page
app.get('/', routes.index);
app.post('/test',function(req,res){
  console.log(req.body);
  res.send("received post");
});
//return list containing users
//app.post('/users', user.list);
//return requested user
app.get('/users/:id', user.get);
//app.post('/users/login', user.login);


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

On the actual webpage, I've got the following javascript code:

var login = $('#login');
  var page = $('#page');
  var register = $('#register');
  var userField = login.find('.user');
  var passField = login.find('.pass');
  var confPassField = login.find('.confpass');
  var form = $('.logform');
  $('#formbutton').on('click',function(){
    if(register.hasClass('hidden')){
      login.addClass('hidden');
      confPassField.val('');
      var logDat = JSON.stringify(form.serializeArray);
      userField.val('');
      passField.val('');
      page.html("Login form submitted");
      $.post(
        form.attr("action"),
        {test:"test"},
        function(data){
          alert("Response: "+data)
        }
      );

    }
like image 838
LucienK Avatar asked Jun 04 '13 22:06

LucienK


1 Answers

If you are posting to / as your log is saying that you are "POST / 404 5ms", you need to change the following line:

app.get('/', routes.index);

to

app.all('/', routes.index);

This will allow a GET or POST to that route. You can also just use app.post() if you are only posting to that route. Hope this helps.

Docs here: http://expressjs.com/api.html#app.all

like image 89
thomallen Avatar answered Oct 14 '22 01:10

thomallen