user1870919
user1870919

Reputation: 11

Express and ajax posting using JQuery

Express doesn't seem to be responding to my ajax request. The post request status appears to be pending for a long time when I look at it in the network tab of the chrome inspector and then fails. This is my express code:

app.configure(function(){
  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.cookieParser());
  app.use(express.session({secret: 'fasfasasasfasfa'}));
  app.use(passport.initialize());
  app.use(passport.session());
  app.use(express.session());
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(app.router);
  app.use(express.static(path.join(__dirname, 'public')));
});

app.post('/test.html', function (req,res) {
  console.log(req.body);
  res.send({ some: JSON.stringify({response:'json' })});
  res.end();
})

And here's my jQuery code:

working = function() {
    console.log("works")
}

$.ajax({
    url:"test.html",
    data: {'name':'hello'},
    type: "POST",
    success: working
  })    

The success function never gets called, and the console log of req.body doesn't seem to work either.

Thanks for the help!

Upvotes: 1

Views: 976

Answers (2)

srquinn
srquinn

Reputation: 10481

You can't use the .html extension on a route in Express as this makes it think its looking for a static resource. Use "pretty URLs" instead.

// Express code...
app.post('test', function(req, res, next){
  // Do stuff to process POST request
});

// AJAX code...
$.ajax({
  url: 'test',
  ...
});

Hope that helps!

Upvotes: 2

Nick Roth
Nick Roth

Reputation: 3077

As you mentioned in the comments, you're getting a status code of 0 back.

Does an HTTP Status code of 0 have any meaning?

Check to make sure you're server is reachable from where you're testing and that the URL your making the request to is actually pointing at the server you want to send the request to.

In other words you probably need to fix this line

url:"test.html",

Upvotes: 2

Related Questions