1

I have a Node.js webserver and I am fetching data from a mysql Server. The fetched Data needs to be displayed now in the frontend as HTML. I am not allowed to use any 3rd Party node.js/JavaScript framework's.

I'm new to Webserver development and i'm having a hard time figuring out how to "transport" the Backend Data to the Frontend.

I have 2 Ideas in my mind but dont know what's the right way to approach this problem...

  1. Send Data via JSON to Client and process it with JavaScript. (Possible? and if yes how?)

  2. Before sending the HTTP response, parse the HTML and insert the data. (Complicated without using Frameworks and too costly ?)

What would be the right way to solve this problem ?

Any Help would be appreciated. Thank's.

Bauer Marius
  • 170
  • 1
  • 12
  • Have you tried it by your own first? If it's possible via framework, it's definitely possible by using pure coding – FieryCat Jun 07 '17 at 19:20
  • yes, i tried some things (xhtmlrequest) without success... i just need a hint in the right direction. – Bauer Marius Jun 07 '17 at 19:26
  • Just search here for your question. Like https://stackoverflow.com/questions/6011984/basic-ajax-send-receive-with-node-js for the first part – FieryCat Jun 07 '17 at 19:28
  • _"yes, i tried some things (xhtmlrequest) without success"_ Why was request not successful? Can you include `javascript` tried at Question? See https://stackoverflow.com/help/mcve – guest271314 Jun 07 '17 at 19:29
  • Thanks i got it now. I thought you can only request files with xhr... I guess i need to do more research next time. – Bauer Marius Jun 07 '17 at 19:39

2 Answers2

2

Solved it like this:

app.js

var http = require('http');  
var url = require('url');

var server = http.createServer(function(req, res) {
    var q = url.parse(req.url, true);
    if(q.filename == "command"){
        res.writeHead(200, {'Content-Type':'application/json'});
        return res.end(some_json);
    }
}

index.html

<script>
    xmlhttp = new XMLHttpRequest();
    xmlhttp.open("POST","http://localhost:8000/command", true);
    xmlhttp.onreadystatechange=function(){
        if (xmlhttp.readyState==4 && xmlhttp.status==200){
            //Process Data
            var jsonObj = JSON.parse(xmlhttp.responseText);
            document.getElementById("test").innerHTML = jsonObj;
        }
    }
    xmlhttp.send();
</script>

<div id="test"></div>
Bauer Marius
  • 170
  • 1
  • 12
0

Something like this?

const http = require('http');
const util = require('util');

const hostname = '127.0.0.1';
const port = 3000;

const server = http.createServer((req, res) => {
  mysql.query("select * from table").then(rows => {
    res.statusCode = 200;
    res.setHeader('Content-Type', 'text/html');
    res.end(`<html><head></head><body>${util.inspect(rows)}</body></html>`);
  })
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});
Sergey Yarotskiy
  • 4,536
  • 2
  • 19
  • 27