Node.js如何添加两个数字? [英] Node.js how to add two numbers?

查看:83
本文介绍了Node.js如何添加两个数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Hy
我想创建客户端服务器。服务器在NOde.js中并与hml / javascript页面通信。

你能不能给我一个例子如何发送到node.js并在javascript中获取变量的html文件的总和?



我尝试过:



//demo.html

 <  !DOCTYPE     html  >  
< html >
< 正文 >

< h1 > 我的第一个标题< / h1 >


< 表单 >
第一个数字:< br >
< 输入 type = 数字 name = firstnumber > < br >
第二个数字:< br >
< 输入 type = number 名称 = lastnumber > < br > < br >
< 输入 类型 = 提交 value = 提交 > < br > < br > < br >
SUM:< br >
< span class =code-keyword>< input type = number name = answer >
< /表格 >


< < span class =code-leadattribute> / body >
< / html >







//server.js

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

console .log( 服务器正在侦听);

解决方案

你好



你必须使用id而不是名字:



 <  输入   类型  = 数字    id   =  firstnumber  >  <   br  >  

< 按钮 类型 = 按钮 onclick = myFunction() > 提交< / button >





和你的js功能将是:



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

// 获取id =firstnumber
x = document .getElementById( firstnumber 。)值;

// 获取id =secondnumber
x = document .getElementById( secondnumber 。)值;

// 如果x不是数字或小于1或大于10

document .getElementById( answer)。innerHTML = x + y;
}
< / script>





希望它有效

最好的问候


< HTML> 
< head>< title>两个数字的总和< / title>< / head>

< script>
函数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>我的第一个标题< / h1>
第一个数字:< br> < input type =numberid =firstnumber>< br>
第二个数字:< br> < input type =numberid =secondnumber>< br>
< button type =buttononclick =myFunction()>提交< / button>< br>
答案:< input type =numberid =answer>

< / body>
< / html>


这是一个比这里给出详细解答更广泛的问题。您的第一步是找出您希望服务器端API看起来像什么 - 通常我会建议一个REST架构,但它只适用于此处。在任何情况下,您都需要定义客户端将联系的URI方案。我建议类似:



http://主机名/计算器/添加?param1 =10¶m2= 5



在HTTP GET上 - 因为你得到结果而不是。我强烈建议使用node package express来完成这项工作:

Node.js Express Framework [ ^ ]。要设置端点,您需要执行以下操作:



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





以上可能需要一些修改 - 不确定是否param1&例如,param2将生成一个字符串concat。

您可以通过chrome扩展名Postman调用URL来测试这一点(邮递员 - Chrome网上应用店 [ ^ ])。即使这种方案也存在缺陷 - 您将客户与提供参数联系在一起 - 您可能也希望能够支持该模式

http:// hostname / calculator / add / 10/5

另外你应该考虑HTTP状态代码以及如何处理错误等。

这个简单代码的另一个缺失是我们假设客户端需要JSON数据 - 读取请求接受标题更容易,我们也应该设置响应标题Content-Type以反映我们正在服务JSON的事实(或者无论如何,如果我们尊重请求接受)。 />


要从客户端拨打电话,您只需使用表格(您可能需要更改方案 - 表格往往与POST一起使用),或者使用

XMLHttpRequest对象 [ ^ ]形成对服务器的调用并使用它的onstatechange事件得到回应。尽管它的名称,该对象用于发送/获取JSON响应。再次,这个细节取决于你的架构。



最后一件事是注意CORS问题 - 你可能不会得到这些与邮递员,然后突然你的服务器停止响应当你让客户端去。客户端可能会首先发送一个OPTIONS请求,因为您的服务器阻止了CORS请求,它将失败 - 您需要对您的服务器进行编码以允许来自任何来源的请求。



Lots想一下! - 第一步是让服务器响应邮递员的请求,我只是从一个回答纯文本hello world的服务开始。


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

<!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

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");

解决方案

Hello

Firs you have to use with id instead of name:

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

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



and your js function will be :

<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


<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:

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".


这篇关于Node.js如何添加两个数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆