我是网络语言方面的新秀,所以如果我的问题很愚蠢,请原谅。基本上我正在尝试将数据从传递html-form
到node.js
服务器,但是即使在Google中搜索了很多之后,我也没有任何相关的例子。那么,有人可以帮我学习这个东西吗?
我发现以下示例用于将数据解析为php
脚本,因此如何调整此代码以将数据传递至node.js
脚本。
码:
<!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
交互。因此,您要做的第一件事就是安装它:
npm install express
对于我的示例,我将安装一个名为的附加中间件body-parser
。
npm install body-parser // this allows us to access req.body.whatever
之后,创建一个简单的服务器来处理您的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}`);
});
这是我们的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>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句