如何将数据从html发送到node.js [英] How to send data from html to node.js

查看:439
本文介绍了如何将数据从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>

这篇关于如何将数据从html发送到node.js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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