21

I am currently using Express.js to create my website. My main server script is called index.coffee. I also created a script called request.js that makes a GET request and displays the response with

  console.log(list);

I have no problems when running the script from the console: node request.js

My question is: How do I make the "Get this list" button on my the page respond to a click by displaying the list on the same page (that is, executing request.js on the server and showing the result)?

app.js

/**
 * Module dependencies.
 */

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

var app = module.exports = express.createServer();

// Configuration

app.configure(function(){
  app.set('views', __dirname + '/views');
  app.set ('view engine', 'coffee');
app.register('.coffee', require('coffeekup').adapters.express);

  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(app.router);
  app.use(express.static(__dirname + '/public'));
});

app.configure('development', function(){
  app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});

app.configure('production', function(){
  app.use(express.errorHandler());
});

app.get('/', function(req, res) {
  res.render('index',{ layout: false });
});



app.listen(3000);
console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);

index.coffee

doctype 5
html ->

  head ->
    body

p -> "hey"

Louis
  • 622
  • 2
  • 10
  • 26
  • 1
    You should make a request handler (like you do for your index page) which executes the code in request.js... You can use an Ajax call to pull this data back and load it in the page. – Fosco Mar 12 '12 at 16:14
  • Ok do you have any tutorials for request handler and an ajax way to be able to pull this data back ^^ ? I am really new to node and Ajax. And thanks for your answer ! – Louis Mar 12 '12 at 16:17
  • You should post your code as it is now. I don't use coffee script so I can't provide a full solution, but surely someone else will be able to help (if the code is here.) – Fosco Mar 12 '12 at 16:19
  • I am going to do that then thanks :) ( the solution in html would also be fine to me ^^ ) – Louis Mar 12 '12 at 16:24

1 Answers1

13

I use plain JS and not coffee script, so here's an example per Fosco's comment (call it server.js):

var express = require('express'),
    list = require('./request.js').Request; // see  template

var app = express.createServer();

app.use(express.static(__dirname + '/public')); // exposes index.html, per below

app.get('/request', function(req, res){
    // run your request.js script
    // when index.html makes the ajax call to www.yoursite.com/request, this runs
    // you can also require your request.js as a module (above) and call on that:
    res.send(list.getList()); // try res.json() if getList() returns an object or array
});

app.listen(80);

Write your index.html file, and save it in the /public subfolder of your node app directory (which is exposed above, via express.static).:

<html>
    <body>
    <div id="button">Get this List</div>
    <div id="response"></div>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <script type="text/javascript">
    $(document).ready(function() {
        $('#button').click(function() {
            // run an AJAX get request to the route you setup above...
            // respect the cross-domain policy by using the same domain
            // you used to access your index.html file!
            $.get('http://www.yoursite.com/request', function(list) {
                $('#response').html(list); // show the list
            });
        });
    });
    </script>
    </body
</html>

If you're including your request.js as a module, it could be as follows:

var RequestClass = function() {
    // run code here, or...
}; 

// ...add a method, which we do in this example:
RequestClass.prototype.getList = function() {
    return "My List";
};

// now expose with module.exports:
exports.Request = RequestClass;

Run node server.js on your server. Then head over to www.yoursite.com/index.html

Community
  • 1
  • 1
Wes Johnson
  • 3,063
  • 23
  • 32
  • 1
    Ok I tried (btw I replaced `
    ` by `
    – Louis Mar 12 '12 at 20:44
  • When you click the button it'll do a full replace of the contents of div#response which might give the appearance of working only 1 time if the content is the same. Otherwise you may have to rebind the click event attached to #button. – Wes Johnson Mar 12 '12 at 21:27
  • I'll update my answer to include how to use request.js as a module. I'm not sure why it'd say you don't have a POST method. My guess is you called a method on `list` that wasn't exposed or was undefined. – Wes Johnson Mar 12 '12 at 21:28
  • Hey everything is working except this: when I try to `res.send("sent");` it works but not with `res.send(list.prototype.getList();)` I think because `list.prototype.getList()` returns an object (should be an array) (I also tried the res.json() way, also not working. How can I do ? – Louis Mar 21 '12 at 14:31
  • `res.json()` seems to work, indeed when i click on `get this list` if in the `response div` there is a text (anything), this text disappear, but then the object is not displayed and I dont understand why. Thanks again – Louis Mar 21 '12 at 14:52
  • I can't say without knowing more about your object. It could be that you're returning a null or false value, or your client ajax is getting a response in the format of a JS object, in which case you can stringify it before pushing it to the response div: `$('#response').html(JSON.stringify(list));` – Wes Johnson Mar 21 '12 at 18:02
  • It's working thanks! the out put is sth like : `["AllAccounts","Cascadin...] – Louis Mar 22 '12 at 13:57
  • But I would Like to do like this : `var tab = new Array; tab=$('#response').html(JSON.stringify(list)); alert(tab[1]); // and then use the tab,` Unfortunately it's undefined, how can i do to have access to tab[1] – Louis Mar 22 '12 at 14:06
  • Sorry, I can't help you with your entire app. You should read up on Javascript & jQuery as you're not using them right. Your second assignment to the tab variable returns a jQuery object, hence why index 1 is undefined. It's not an array. You can simply assign your list var to tab, it's already an array. – Wes Johnson Mar 23 '12 at 16:08
  • You can also do this with `fetch` in ES6 nowadays – information_interchange Oct 14 '18 at 18:32