2

I'm new to CompoundJS and I'm not too sure if this is the correct behaviour.

I'm starting the server on PROD mode with the following code:

NODE_ENV=production compound server 8081

Then I hit:

http://localhost:8081/categories/

I was excepting to see some JSON being retrieved from the server.

Instead, it renders a page like this:

enter image description here

Pablo
  • 2,540
  • 1
  • 18
  • 26
  • Why did you expect a JSON response? – robertklep May 11 '13 at 05:29
  • Hi Robert, I expected a JSON response so I can use it in the front-end app. Also, I don't want expose this interface to people.. (does it make sense?) – Pablo May 11 '13 at 08:05
  • 1
    It does make sense, but you have to tell your controller to generate JSON instead of render a template. Instead of `render()`, you could try using `send(YOUR_OBJECT)` to get it to return JSON. – robertklep May 11 '13 at 08:45
  • 1
    Thanks! Now I see how it works behind the scenes. I can also call ```http://localhost:8081/categories.json``` and that would do the trick. – Pablo May 11 '13 at 08:58
  • Ah, that's even better :) I don't know CompoundJS well enough so I didn't know about the `.json` trick :) – robertklep May 11 '13 at 09:14

1 Answers1

2

As @Pablo mentioned in the comments, just use .json in the call to your controller.

As in the following:

GET http://localhost:3000/categories.json

It is expected that your controller will handle both, as is the case in generated controllers.

A specific example: [approot]/app/controllers/category_controller.js

In JavaScript:

action(function index() {
    this.title = 'Categories index';
    Category.all(function (err, categories) {
        respondTo(function (format) {
            // Use format.json and the send method to return JSON data when 
            // .json is specified at the end of the controller
            format.json(function () {
                send({code: 200, data: categories});
            });
            format.html(function () {
                render({
                   categories: categories
                });
            });
        });
    });
});

In CoffeeScript:

action index = ->
  @title = "Categories index"
  Category.all (err, categories) ->
    respondTo (format) ->

      # Use format.json and the send method to return JSON data when 
      # .json is specified at the end of the controller
      format.json ->
        send
          code: 200
          data: categories


      format.html ->
        render categories: categories
Pablo
  • 2,540
  • 1
  • 18
  • 26
absynce
  • 1,399
  • 16
  • 29