Click here to Skip to main content
15,396,019 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more: , +
Hy I want to create client-server . The server is in NOde.js and comunicate with hml/javascript page.
Can you someone make me one example how to send to node.js and get back the sum to html file for variable in javascript?

What I have tried:

//demo.html
HTML
<!DOCTYPE html>
<html>
<body>

<h1>My First Heading</h1>


<form>
  First number:<br>
  <input type="number" name="firstnumber"><br>
  Second number:<br>
  <input type="number" name="lastnumber"><br><br>
	<input type="submit" value="Submit"><br><br><br>
    SUM:<br>
  <input type="number" name="answer">
</form>


</body>
</html>



//server.js
JavaScript
var http = require("http");
http.createServer(function(req, res) {
  res.writeHead(200, {"Content-Type": "text/plain"});
  res.end('Hello q\n');
}).listen(8080,'127.0.0.1');

console.log("Server is listening");
Posted
Updated 22-Apr-22 19:05pm

Hello

Firs you have to use with id instead of name:

HTML
<input type="number" id="firstnumber"><br>

<button type="button" onclick="myFunction()">Submit</button>


and your js function will be :

JavaScript
<script>
function myFunction() {
    var x, y;

    // Get the value of the input field with id="firstnumber"
    x = document.getElementById("firstnumber").value;

// Get the value of the input field with id="secondnumber"
    x = document.getElementById("secondnumber").value;

    // If x is Not a Number or less than one or greater than 10
    
    document.getElementById("answer").innerHTML = x + y;
}
</script>


hope it works
best regards
   
Comments
Member 12435531 16-Oct-16 5:34am
   
Hello

Thank you for answer and help.
Now is working:)

<!DOCTYPE html>







My First Heading


First number:
Second number:

Answer:




Now I want to make the function is not compute in html,but in the node.js server side.
The main goal is create simple server-client comunication.

Tha html send data to node.js server, the node is compute the sum of the numbers and send back to the javascript function in html.
Ali Majed HA 16-Oct-16 6:29am
   
If it works, Would you please accept and vote the solution? Thanks in Advance
Keith Barrow 18-Oct-16 4:20am
   
Your solution doesn't answer the question - it takes two input values and adds them, all on the client side. NodeJS isn't involved at all, and there is no server.
I'm not saying your solution is bad, it'll work, but it isn't what is being asked for.
<html>
<head><title>Sum of two numbers</title></head>

  <script>
  function myFunction() {
      var x, y,sum;
      x = parseFloat(document.getElementById('firstnumber').value);
      y = parseFloat(document.getElementById('secondnumber').value);
      sum = x + y;
      document.getElementById('answer').value = sum;
  }
  </script>


<body>
  <h1>My First Heading</h1>
  First number: <br> <input type="number" id="firstnumber"><br>
  Second number:<br> <input type="number" id="secondnumber"><br>
  <button type="button" onclick="myFunction()">Submit</button><br>
  Answer: <input type="number" id="answer">

</body>
</html>
   
This is a broader question than can be given a detailed answer here. Your first step is to work out what you want your server side API to to look like - normally I'd suggest a REST architecture, but it only semi-applies here. In any case you need to define the URI scheme, that the client will contact. I'd suggest something like:

http://hostname/calculator/add?param1=10¶m2=5

On an HTTP GET - as you are getting the result as opposed. I'd strongly recommend the node package express for this work:
Node.js Express Framework[^]. To set up the endpoint you'd do something like:

JavaScript
app.get('/calculator/add', function (req, res) {
    response = {
      result: req.query.param1 + req.query.param2,
   };
   res.end(JSON.stringify(response));
})


The above will probably need some fettling - not sure whether param1 & param2 will result in a string concat for example or not.
You can test this by calling the URL via the chrome extension "Postman" (Postman - Chrome Web Store[^]). Even this scheme has deficiencies - you're tying the client in to providing parameters - you might want to be also able to support the schema
http://hostname/calculator/add/10/5
Also you should think about HTTP status codes and how to handler errors etc.
The other thing "missing" with this simple code is the we're assuming the client wants JSON data - reading the request "Accept" header is more accommodating, also we should set the response header "Content-Type" to reflect the fact we're serving JSON (or whatever, if we're honouring the request Accept).

To call from the client you can just use a form (you might need to change the scheme - forms tend to work with POST), or use
XMLHttpRequest object[^] to form the call call to the server and use it's onstatechange event to get the response. Despite it's name, this object is used to send/get JSON responses. Again, the detail of this depends on your schema.

The final thing is watch out for CORS problems - you probably won't get these with postman, then suddenly your server stops responding when you get the client going. The client will probably send an OPTIONS request first, which will fail as your server prevents CORS requests - you need to code your server to allow requests from any origin.

Lots to think about! - Step one is getting a server responding to requests from postman, I'd just start with one that answers a plain-text "hello world".
   
So we will use query string for this solution, so type this url in the browser localhost:9000/add?number1=25&number2=40.

app.get('/add', function (req, res) {
let sum = Number(req.query.number1) + Number(req.query.number2);
res.send(`Sum of two numbers is ${sum}`);
})

In the above code, we will first get the value of both the numbers like this, so req.query.number1 will give 25 and req.query.number2 will give 40. Now the value which we get i.e 25 and 40 both are in string form so if we directly add them then it will give result as 2540 means it does concatenation of the two strings and we don't want this. So for addition we need to convert both string values into number.For that we use Number() function. So now 25+40 will give the result 65 and then it will be stored in variable sum and then we are printing it using res.send().
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900