javascript 如何将数据从 html 发送到 node.js

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/52675257/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 10:00:36  来源:igfitidea点击:

How to send data from html to node.js

javascripthtmlnode.js

提问by coder

I'm a rookie in web languages so please do excuse me if my question is foolish. Basically I'm trying pass data from html-formto node.jsserver but even after searching a lot in google I couldn't get any relevant examples. So, can anyone please help me to learn this thing ?

我是网络语言的新手,所以如果我的问题很愚蠢,请原谅。基本上我从试图将数据传递html-formnode.js服务器,但即使是在谷歌搜索了很多后,我不能得到任何相关的例子。那么,任何人都可以帮我学习这个东西吗?

The following example I found for parsing data to phpscript so how can I tweak this code to pass data to node.jsscript.

我发现以下示例用于将数据解析为php脚本,因此如何调整此代码以将数据传递给node.js脚本。

Code:

代码:

<!DOCTYPE html>
<html>
<body>

<form action="/action.php" method="get" target="_blank">
 First name: <input type="text" name="fname"><br>
 Last name: <input type="text" name="lname"><br>
<input type="submit" value="Submit">
 </form>

<p>Click on the submit button, and the input will be sent to a page on the server called "/action_page.php".</p>

回答by Dzenis H.

I would highly suggest using a framework like Expressfor a more pleasant Node.jsinteractions. So the first thing you would have to do is install it:

我强烈建议使用一个框架Express来进行更愉快的Node.js交互。所以你要做的第一件事就是安装它:

npm install express

And for my example, I'll install an additional middleware, called body-parser.

对于我的示例,我将安装一个额外的中间件,称为body-parser.

npm install body-parser  // this allows us to access req.body.whatever

After that make a simple server to handle your POSTrequests, like this:

之后制作一个简单的服务器来处理您的POST请求,如下所示:

const express = require('express');
const bodyParser = require('body-parser');
const app = express();

app.use(bodyParser.urlencoded({ extended: true })); 

app.post('/example', (req, res) => {
  res.send(`Full name is:${req.body.fname} ${req.body.lname}.`);
});

const port = 8080;

app.listen(port, () => {
  console.log(`Server running on port${port}`);
});


And here is our HTML form: So we're sending our data to our localhost[http:// 127.0.0.1], port 8080and a route of /example--> All that was configurated in our little Expressserver

这是我们的 HTML 表单:所以我们将数据发送到localhost[http://127.0.0.1]、端口8080和路由/example--> 所有这些都在我们的小Express服务器中配置

<form action="http://localhost:8080/example" method="POST">
  First name: <input type="text" name="fname"><br>
  Last name: <input type="text" name="lname"><br>
 <button type="submit">Send to backend</button>
</form>

回答by Z_z_Z

You've got a couple of different ways to solve your problem here.

您在这里有几种不同的方法可以解决您的问题。

Here's the simplest:

这是最简单的:

You can use the HTML form directly like you've shown in your example. But you need to understand what it's doing under the hood. So I'll give you a quick explanation.

您可以像示例中所示那样直接使用 HTML 表单。但是你需要了解它在幕后做了什么。所以我会给你一个快速的解释。

Here's the bare bones HTML file that you need to write:

这是您需要编写的基本 HTML 文件:

<!DOCTYPE html>
<html>
  <body>
    <form action="/your-node-server-route-name" method="POST">
     <input name="give-me-a-name" type="text" />
     <button type="submit">Send This Bad Boy To The Server</button>
    </form>
  </body>
</html>

So here's what's going on.

这就是正在发生的事情。

In the formtag the actiondefines whereyou want to send the data you collect from your user. This is the URL of the route you set up for handling this data on your node server (NOTE: this could be any server, not just node). So if you have a server running at http://localhost:3000and your route for handling this data is /handle-form-data, then you would write your action as action="http://localhost:3000/handle-form-data"just like that. If your node server also serves this HTML page, then you can use a relative path to point to your route like this: action="/handle-form-data".

form标签中,action定义您要将从用户那里收集的数据发送到何处。这是您为在节点服务器上处理此数据而设置的路由的 URL(注意:这可以是任何服务器,而不仅仅是节点)。因此,如果您有一台服务器运行在http://localhost:3000并且您处理这些数据的路线是/handle-form-data,那么您将action="http://localhost:3000/handle-form-data"像这样编写您的操作。如果您的节点服务器还服务于这个HTML页面,那么你可以用它来点相对路径这样的路线:action="/handle-form-data"

The methoddefined what HTTP method you want to use when submitting your form. For sending datayou want to use the POSTmethod. So we write method="POST"to let the node server know we are making a post request. If you are using Express as your web server framework, then you need to configure your route to handle post requests like so:

method你想提交表单时使用何种HTTP方法定义。对于发送数据,您要使用该POST方法。所以我们写信method="POST"让节点服务器知道我们正在发出一个 post 请求。如果你使用 Express 作为你的 web 服务器框架,那么你需要配置你的路由来处理 post 请求,如下所示:

app.post("/handle-form-data", (req, res) => {
  // Do Something in Node here
})

The inputtag nested inside the formis used to collect user input. You have to assign a nameproperty to your data so that you can recognize this piece of data on the server. You can give it any name you like. So, for instance, if you want to collect a user's birthday, then write name="user-birthday". The type="text"just tells the browser to render a certain type of style.

所述input嵌套内的标签form被用于收集用户输入。您必须为name您的数据分配一个属性,以便您可以在服务器上识别这条数据。你可以给它任何你喜欢的名字。因此,例如,如果您想收集用户的生日,请编写name="user-birthday". 在type="text"刚刚告诉浏览器渲染某种类型的风格。

Finally, the buttontag will allow the user to send the form to your server. Give the button a type="submit"to tell the browser that when a user clicks the button, that the form should be sent.

最后,该button标签将允许用户将表单发送到您的服务器。给按钮 atype="submit"告诉浏览器,当用户单击按钮时,应该发送表单。

...............................................

……………………………………………………………………………………………………………………………………………………………………………………………………

And that's it! That's the basics of handling forms.

就是这样!这就是处理表单的基础知识。

But be aware that there are a lot of drawbacks to this simple approach that you may want to take care of in the future. For that I recommend looking at the fetch()method used in Javascript, or using a library like Axios. They will make your life a whole lot easier

但请注意,这种简单的方法有很多缺点,您可能希望在将来加以解决。为此,我建议查看fetch()Javascript 中使用的方法,或使用Axios. 他们会让你的生活更轻松