Community
Community

Reputation: 143

Nodejs - A better way to handle ajax request to the server

Now I ran into a problem with managing ajax requests on nodeJS server. Currently I have this system it works, but it's ugly and not that efficient.

router.post('/get', function(req, res) {
  var request = req.body.request;
  if (request == null) {
    res.json({success: 'false', error: 'Response returned null'});
    return;
  }
  if (request == "render_page") {
    var page = req.body.page;
    if (page == null) {
      res.json({success: 'false', error: 'Page returned null'});
      return;
    }
    res.render(page);
  } else if (request == "render_article") {
    var temp = {
      articles: [
        {title: 'ABC', text: 'This is a test article'},
        {title: 'XYZ', text: 'Just another random article'}
      ]
    };
    res.render('template/article-format', temp);
  } else {
    res.json({success: 'false', error: "Unknown request " + request});
  }

Is there a better way to do this and even maybe make it dynamic? Also the server likes to crash if something goes wrong so there's that.

Upvotes: 0

Views: 481

Answers (1)

Olivercodes
Olivercodes

Reputation: 1058

You seem to be fighting with the concepts of GET and POST. GET requests are supposed to be used for fetching things (like pages). Yet, you have specified a POST request, then named it /get, and then put the context in the request body.

If you simply leveraged some parameters in your GET requests, then you don't need to send a post with body (which I'm assuming you are using a POST request because you thought you needed to be able to send the request context data, in this case the page name).

So, you have a bunch of get requests that are being called as post requests. Really what you want is something like this:

router.get('/page/:page', function(req, res) {
  var page = req.params.page;
  // Logic here
});

And for handling the "null" page, you just route them to the /page url automatically (since if there is no parameter, it is just the /page url).

For further reading, I'd look over:

http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html

http://expressjs.com/4x/api.html#req

Upvotes: 1

Related Questions