Send data to the client without using an additional url

2

Hello. What I want to know is the best way to send data to the client and this data will be received through a function (which can be executed in a click).

In the example below I will render a page (I am using express in node.js):

app.get('/exemplo', function (req, res) {
  res.render('exemplo.html');
});

But if I want to submit data to the rendered page, will I be forced to use an additional url ? As below:

app.get('/exemplo', function (req, res) {
  res.render('exemplo.html');
});
var data = {...}
app.get('/exemplo/data', function (req, res) {
  res.send(data);
});

Or could you do both using the same url ? Or would there be some other way to send data, for example, user data to the page, using expressJs .

Note: I do not use the Jade preprocessor.

Thank you in advance.

    
asked by anonymous 09.07.2016 / 21:22

1 answer

1

You can use the same route in Express and send the data in a query string , as a GET.

You can do this with ajax and then on Express use .query , first argument ( req ) in the controller.

An example would look like this:

In JavaScript, using ajax :

var data = {foo: 'bar'};
ajax(data, function(res) {
    console.log('Resposta do servidor:', res);
});

And on Node / Express, using req.query :

app.get('/exemplo', function (req, res) {
  var txt = req.query.foo + ' bar';
  res.render({resposta: txt}); // vai mandar de volta a string para o JS
});
    
10.07.2016 / 00:05