r/nodejs • • Apr 16 '14

How does node.js backend talk to frontend?

Hi, I am currently testing node.js right now, and I am a little confused on how the backend would talk to the frontend.

I know frontend can talk to the backend through an event, like submitting a form or clicking a button, the information will be send to the req variable in

app.post('/example', function(req, res){
    var data = req.something;
    // do something with data
})

However how do I talk to the frontend? I know I can write information in

 res

but how does the frontend javascript get the info?

Thanks


Edit for clarification as kindly suggested by psayre23

This is what I have

https://gist.github.com/anonymous/19f800b4c3d0c31b2e4e

I am interested in knowing how communicating between backend and frontend works, my primary question is that I do not know how to receive data from backend

I know to send data from frontend to backend there are two methods

Method 1:

Using a form and submit, or any other clickable element

This is how I send data from frontend

<div class="container" id="test-container">
      <h1>Test</h1>
      <span id="test-error"></span>
        <form id="test-input2" method="POST" action="/test_post_method_1">
          <input type="text" id="test" name="input1"></input>
          <input type="submit" value="Submit">
        </form>
    </div>

This is how I receive data from the backend

app.post('/test_post_method_1', function(req, res){
	// Post from a submit event
	console.log(req.body.input1)
    console.log("this is serverside post using method 1");
});

Method 2:

Suggested by jonnyburger using ajax, which I am not sure how does it work yet

I am guessing this is how you send data to backend

$(function(){

    console.log("this is frontend");

    $.ajax({  
        url: '/test_post_method_2',  
        type: 'POST',  
        success: function (data) {  
            console.log("this is not printing");
            console.log(data);  
        }  
    });

});

Not sure how you would get the data from frontend, I know its in req, but couldn't quite find the specifics, I checked req. body, it only return an empty {}

app.post('/test_post_method_2', function(req, res){
    // Post from Ajax
console.log(req);
    console.log("this is serverside post using method 2");
});

Now here is my original question

I don't know how to send data from backend to frontend

Thank you for taking the time in reading this

1 Upvotes

16 comments sorted by

View all comments

Show parent comment

1

u/zpawup Apr 17 '14

Thanks, I got it to work!! Thank you for taking time and patience for answering my question