Retrieving data from a Node.js file and displaying it on an HTML / JS page

I am new to Node.js and this is my first project with it. I created a Node.js file called test.js. It has an array, say a.

Now I want to create an HTML file that calls this test.js on a button click event. Then get the data from this file and publish it in a table in the HTML file.

I already wrote a Node.js file and I can see the results on console.log (a). But I cannot figure out how to send this array in HTML when it asks for it.

Meanwhile, I googled and compiled some code. The request arrives at the server, but I always get an error message from the server. Why is that?

Client side -

function fetch() { $.ajax({ type: 'POST', url: "http://127.0.0.1:8888", data: 'China', datatype: 'json', success: function (data) { alert("hi"); var ret = jQuery.parseJSON(data); $('#q').html(ret.msg); }, error: function (xhr, status, error) { alert("hii"); } }); 

Server side:

 http.createServer(function(request, response) { console.log("Request received"); response.writeHeader(200, {"Content-Type": "application/json"}); request.on('data', function (chunk) { console.log(chunk.toString('utf8')); consol.log(result); response.write(JSON.stringify({data : result})); }); response.end(); }).listen(8888); 

I can see China on the console. But I do not return an array of results back to the client. The result is an array, and I get its value on the console. I just won’t return it to the client. Any help?

+8
javascript html
source share
2 answers

You should start by setting up a server to service requests. I use expressjs for this - http://expressjs.com/

This will allow you to run nodejs as a web application.

Setting up a route in express-JS to serve your data - http://expressjs.com/api.html#express

 var express = require('express'); var app = express(); app.get('/data', function(req, res){ res.send('hello world'); //replace with your data here }); app.listen(3000); 

Open a browser and enter http://MY_SERVER_ADDR:3000/data , and you will see your output there.

Then you will need to bind the even handler to your HTML file, which will trigger the $ .get () request when it starts. Add the previous url to your data in your $ .get call and do something with it.

 $('.my_selector').click(function(){ $.get('http://MY_SERVER_ADDR:3000/data', {}, function(data){ console.log(data) }); }); 

That should make you go.

+14
source share

After struggling with the same issue, I found that this is where the template engine comes in node-picture. AJS solved this for me, but there are many more available. This article compares 10 template engines.

0
source share

All Articles