如何将数据从html发送到node.js
我是网络语言的新手,所以如果我的问题是愚蠢的,请原谅我。基本上我正在尝试将数据从 html-form
传递到 node.js
服务器,但即使在谷歌搜索了很多我无法得到任何相关的例子。那么,任何人都可以帮我学习这个东西吗?
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-form
to node.js
server 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 ?
以下我发现的解析数据的例子 php
脚本所以如何调整此代码以将数据传递到 node.js
脚本。
The following example I found for parsing data to php
script so how can I tweak this code to pass data to node.js
script.
代码:
<!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>
我强烈建议使用像 Express
这样的框架,以获得更愉快的 Node.js
互动。所以你要做的第一件事就是安装它:
I would highly suggest using a framework like Express
for a more pleasant Node.js
interactions. So the first thing you would have to do is install it:
npm install express
在我的例子中,我将安装一个额外的中间件,名为 body-parser
。
And for my example, I'll install an additional middleware, called body-parser
.
npm install body-parser // this allows us to access req.body.whatever
然后制作一个简单的服务器来处理你的 POST
请求,如下所示:
After that make a simple server to handle your POST
requests, like this:
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}`);
});
这是我们的HTML表格:
所以我们将数据发送到 localhost
[http:// 127.0.0.1],端口 8080
并且一条 / example
- >所有在我们的小 Express
服务器中配置的
And here is our HTML form:
So we're sending our data to our localhost
[http:// 127.0.0.1], port 8080
and a route of /example
--> All that was configurated in our little Express
server
<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>