-3

I'm setting up my first server with node.js, but I don't know how to connect a client and that server. I don't want to use jquery, and all the questions I could find about this involved jquery or were about different languages. Does anyone know how to do this?

Edit: I have a connection between the server and client, but the response has nothing in it. The code for my server is here, and the code for my client is here (in the folder "Multiplayer").

object-Object
  • 1,587
  • 1
  • 12
  • 14

3 Answers3

1

Do something like this to setup a Node.js HTTP server listenning on port 8080.

The client will send GET requests using AJAX.


index.html

<html>
  <head>
    <script>
      var xhttp = new XMLHttpRequest();
      // Create a function callback, called every time readyState changes
      xhttp.onreadystatechange = function()
      {
        // When the response has been received with status 200
        // Update the element div#response-holder
        if (this.readyState == 4 && this.status == 200)
        {
          var txtDisplay = elem document.getElementById("response-holder")
          txtDisplay.innerHTML = this.responseText;
        }
      };

      // Send a GET request to /api, asynchronously
      xhttp.open("GET", "/api", true);
      xhttp.send();
    <script>
  </head>
  <body>
    <div id="response-holder"></div>
  </body>
</html>"

server.js

// Load the http and fs (filesystem) modules
var app = require("http");
var fs = require("fs");

// Serve the "/index.html" home page on port 8080
app.createServer(function (req, resp)
{
  fs.readFile("index.html", function(err, data)
  {
    resp.writeHead(200, {'Content-Type': 'text/html'});
    resp.write(data);
    resp.end();
  }
  );
}
).listen(8080);

// Also answer to GET requests on "/api"
app.get('/api', function(req, resp)
{
  var responseStr = "Hello World!";
  resp.status(200);
  resp.setHeader('Content-type', 'text/plain');
  return resp.send(responseStr);
}
);

Here is a W3Schools tutorial on AJAX: https://www.w3schools.com/js/js_ajax_intro.asp

Taz8du29
  • 43
  • 6
0

You may do that with vanilla JavaScript, using Fetch API.

Assuming that Node will provide you some URLs, you can get, post, etc., through fetching them.

More on how that works here: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API

-2

TCP connection between client and Node server will be the option. Here's a sample code snippet:

var ser = require('ser');

var clientSer = new net.Socket();
clientSer.connect(1220, '127.0.0.1', function() {
    console.log('Connected');
    client.write('Hello, Connection Established!');
});

clientSer.on('data', function(data) {
    console.log('Received: ' + data);
    client.destroy(); // kill client after server's response
});

clientSer.on('close', function() {
    console.log('Connection closed');
});

Node tutorial: https://www.w3schools.com/nodejs/nodejs_intro.asp

pranav888
  • 1
  • 1