1

How can I send an obect to javascript in the client's side? I asked earlier a question and was answered and accepted the question because I couldnt check the answer on the computer: Client receive json object to javascript

I still dont understand how to send the data to the client I tried req.send/render and it didnt get to function in the client's side.

client:

$.get('127.0.0.1:3000', {mydata: 'content'}, function(response){
   //callback triggered when server responds
   console.log(JSON.stringify(response));
});

server:

  app.get('/', function (req, res) {
      if(req.params.mydata === 'content'){
        res.end("you sent content");
      }  else {
        res.end("you sent something else");
      }
    });

Thank you!

Community
  • 1
  • 1
asdsd
  • 99
  • 1
  • 9
  • Ok. After starting your application, if you make a browser request to `localhost:3000` (or `127.0.0.1:3000)`, do you receive your response, like `"you sent something else"`? – Rodrigo Medeiros Dec 10 '14 at 16:54
  • yes. you can say my question in simple is how to make it write 'you sent content' – asdsd Dec 10 '14 at 17:00
  • Nice. So you already done the `"send the data to the client"` part in the server. Now, you have to debug your client side. Do you see anything in the browser console? If you put just a `console.log('test')` inside the callback in the ajax request, can you see it logged? – Rodrigo Medeiros Dec 10 '14 at 17:08
  • But even when I delete the client part shown above it shows you sent something else. I'm not sure i understood you. I opend the browser and in the console i wrote : console.log('test') and got: 2 test undefined – asdsd Dec 10 '14 at 17:12
  • No problem. When I told you to put a `console.log('test')` in the callback, I mean put it in your client side code, like: `$.get('127.0.0.1:3000', {mydata: 'content'}, function(response){ //callback triggered when server responds console.log('test'); });`. Just to see if your client code is really executing the callback. – Rodrigo Medeiros Dec 10 '14 at 17:15
  • It didnt enter, when i get over this line ($.get) i get : XMLHttpRequest cannot load %3127.0.0.1:8080/?mydata=content. Cross origin requests are only supported for protocol schemes: http, data, chrome-extension, https, chrome-extension-resource.VM104:1 E.extend.ajaxVM104:1 E.extend.getMessageScript.js:2 (anonymous function)VM104:1 (anonymous function)VM104:1 (anonymous function)VM104:1 E.extend.eachVM104:1 E.extend.ready – asdsd Dec 10 '14 at 17:21
  • Did you see the error message? It says your browser is trying to call `127.0.0.1:8080/` and not `127.0.0.1:3000`. Have you tried to use the full `url`, like `http://127.0.0.1:3000`? Are you using any kind of proxy or something? – Rodrigo Medeiros Dec 10 '14 at 17:38
  • writing the full path helped - i dont see the error anymore. But it still doesnt go inside the function – asdsd Dec 10 '14 at 17:43
  • Nice. Try to use [`$.ajax()`](http://api.jquery.com/jquery.ajax/) instead of `$.get()`. An example: `$.ajax({ url: 'ttp://127.0.0.1:3000', data: {mydata: 'content'}, dataType: 'xml', complete : function(){ alert("foo"); }, success: function(xml){ alert("bar"); } });` – Rodrigo Medeiros Dec 10 '14 at 17:54
  • it prints foo. and when i pass on it in debug i get this error: `XMLHttpRequest cannot load http://127.0.0.1:1337?mydata=content. Cross origin requests are only supported for protocol schemes: http, data, chrome-extension, https, chrome-extension-resource.VM154:1 E.extend.ajaxMessageScript.js:7 (anonymous function)VM154:1 (anonymous function)VM154:1 (anonymous function)VM154:1 E.extend.eachVM154:1 E.extend.ready` Maybe the problem is in the server side? – asdsd Dec 10 '14 at 17:59
  • the port is 1337 - not 3000 or 8080, there was a mix up there..hh but i checked everything with the currect port – asdsd Dec 10 '14 at 18:01
  • Ok, nice. And also change the `dataType` in the ajax request to `json`. – Rodrigo Medeiros Dec 10 '14 at 18:02
  • Ok, i changed to json and also noticed you wrote ttp instead of http and i copied it.. hh now i changed to http and it works without the error but still prints foo – asdsd Dec 10 '14 at 18:06
  • Just to make sure: you are using port `3000` in the client side and in the server side, right? If so, put a `console.log('test')` inside your `app.get` just to see if the request is reaching the server. Don't forget to restart your server app. – Rodrigo Medeiros Dec 10 '14 at 18:15
  • the request is reaching the server – asdsd Dec 10 '14 at 18:18
  • Well, you already have the `success` event in your ajax request. Remove the `complete` event and add the `error` event. The `error` and `success` events never occur in the same request. Put it like: `error: function (jqXHR,error, errorThrown) { console.log(error); }`. – Rodrigo Medeiros Dec 10 '14 at 18:28
  • I got this error : `XMLHttpRequest cannot load http://127.0.0.1:1337/?mydata=content. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:1337' is therefore not allowed access. MessageScript.js:9 error` in the browser console it print 'error' – asdsd Dec 10 '14 at 18:34

3 Answers3

2

Instead of using res.end, you want to use res.json -- this will set the HTTP Content-Type header appropriately so your data is actually passed as JSON. Here's an example route:

app.get('/', function(req, res) {
  if (req.params.mydata === 'content') {
    res.json({ message: 'you sent content' });
  } else {
    res.json({ message: 'you sent something else' });
  }
});

Hope that helps!

rdegges
  • 32,786
  • 20
  • 85
  • 109
  • 1
    thank you for your answer. but i asked how to send the client data using this code, not necessarely json,any data – asdsd Dec 10 '14 at 16:56
  • Ah, well in that case you can use res.send() -- but the thing is, this won't work in your example because your jQuery code is looking for JSON stuff specifically -- that's why I said use `res.json`. If you want to send non-JSON data, keep doing what you're doing, but modify your jQuery code to look for strings instead of JSON. – rdegges Dec 10 '14 at 19:31
2

Use res.send()

app.get('/', function (req, res) {
    req.params.mydata === 'content'
        ? res.send("you sent content")
        : res.send("you sent something else");
});
Evgeny Samsonov
  • 2,730
  • 4
  • 19
  • 28
0

In your server code, when you do:

req.params.mydata

, you're trying to get mydata from a property mapped in one of your routes like:

'http://127.0.0.1:1337/:mydata'

which is not your case. Your're sending an object {mydata: 'content'} through a query string, like:

'http://127.0.0.1:1337/?mydata=content'

So, to get this data on your server code, you have to do:

if (req.query.mydata === 'content') {
  // do something
}

or even

if (req.param('mydata) === 'content') {
  // do something
}

For more information on how to handle received data, take a look at the express.js Request docs. As @rdegges pointed out, if you want to send json data, you should use res.json instead of res.end. But, in your case, since your are making a request from your client side and having an No 'Access-Control-Allow-Origin' (you said it in your comments), you have two options:

  • Set the headers of your server response, as explained here, or;
  • Make your server code return a jsonp response, instead of just json, for example res.jsonp({ message: 'you sent content' });

If you take the second option, you should prepare your client code to handle this, adding the dataType: 'jsonp':

$.ajax({
  url: 'http://127.0.0.1:1337/',
  data: {
    mydata: "content"
  },
  dataType: 'jsonp',
  success: function (json) {
    console.log(json);
  },
  error: function (jqXHR, error, errorThrown) {
    console.log(error);
  },
  type: 'GET'
});
Community
  • 1
  • 1
Rodrigo Medeiros
  • 7,814
  • 4
  • 43
  • 54
  • first, realy thank you for all your help! I tried doing so and got the error : cant set headers after they are sent. I think its because i have res.render('main') before these line and this page holds the client's javascript – asdsd Dec 11 '14 at 13:53
  • Yes, that's correct. If you call a `res.render()` before your `res.end()` or `res.send()` or whatever, you'll get an error, because the response was already sent. – Rodrigo Medeiros Dec 11 '14 at 14:04
  • so how can i send the main which holds tha javascript that listens to json data and send also data from the server – asdsd Dec 11 '14 at 14:05
  • By what you said in your question, I understand that you have client side already loaded in a browser and want to make a request to your server side, and have data retrieved. – Rodrigo Medeiros Dec 11 '14 at 14:18
  • In the app.get('/') i want to send the page to display as well as the data. and just tried res.render('main',data) and it didnt work – asdsd Dec 11 '14 at 14:20
  • In this case, you have to use a template engine, like `jade` or `ejs`, or other. Take a look at [this example](http://cwbuecheler.com/web/tutorials/2013/node-express-mongo/), with Jade. You can skip the first part, I think. Take a look at part 2. – Rodrigo Medeiros Dec 11 '14 at 15:07
  • I have jade and working with it. but how does it help? I fi read the article will i be able to send the data? – asdsd Dec 11 '14 at 15:17
  • I didn't know you already had `jade`. Well, if you have `jade` up and running, you just have to pass the data to your `jade` template, like `res.render('main', data)`, where `data` must be a javascript object, like `{ foo: 'bar' }`. You must guarantee that you don't try to play with the `response` object after `render` is called. Then, in your `jade` template, you can access this `{ foo: 'bar' }` object. – Rodrigo Medeiros Dec 11 '14 at 15:31
  • But i want the data to get to the javascript of the main page (which is jade) first. and the javascript handles the data and display it – asdsd Dec 11 '14 at 15:43
  • @asdsd I think your cenario goes far beyond your initial question. To be able to help your the way you need, I think you should ask another question and explain the design of your app and what you want to accomplish with it. In this new question, you can pass all information me and other people need to help you. It's not that I don't want to help you, it's just that I'm not understanding your app flow and the problem that you're having. – Rodrigo Medeiros Dec 11 '14 at 15:50
  • I actually thought my question was simple untill hours of questions..hh I asked a new question here, I hope I explained everything good enogh http://stackoverflow.com/questions/27427358/server-sends-data-to-client – asdsd Dec 11 '14 at 16:11