Use jquery $ .ajax to get node.js script output, not its code

I am creating a small prototype and have the following problem:

I am trying to establish a connection between jQuery on the client side and the server side of node.js; when I make an ajax jQuery request to my node.js code, it just gives me the code, not the code output.

What am I doing wrong?

Part of client.js:

$.ajax({url      : './../includes/get_data.js', 
        success  : function(data) {
          alert('success!');
        },
        error    : function(data) {
          alert('error!');
        }
});  

get_data.js:

var fs = require('fs');

console.log('test');

When I make a request to get_data.js, I want: test

But instead, I get the source code:

var fs = require('fs');

console.log('test');

Many thanks

+3
source share
2 answers

.js, Node. , HTTP- ( http://nodejs.org/), , console.log( ).

:

app.js, node app.js, localhost 1337:

var http = require('http'),
    ajaxResponse = { 'hello': 'world' },
    htmlContent;

htmlContent  = "<html><title></title><head>";
htmlContent += "<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js'></script>";
htmlContent += "<script>$(function() {$.ajax({url:'/ajax',success:function(data){alert('success!');console.log(data);},error:function(data){alert('error!');}});});</script>";
htmlContent += "</head><body><h1>Hey there</h1>";
htmlContent +="</body></html>";

http.createServer(function (req, res) {   
  if (req.url === '/ajax') {
    res.writeHead(200, {'Content-Type': 'text/json'});
    res.end(JSON.stringify(ajaxResponse));
  } else {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.end(htmlContent);  
  }  
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');
+5

, URL- ( Node), , , get_data.js ?

, express - http://expressjs.com/api.html#express.

0

All Articles