html - Node.js - 如何从 html 发送数据以表达

标签 html node.js forms node.js-client http-post

这是 html 中的表单示例:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>CSS3 Contact Form</title>
</head>
<body>
<div id="contact">
    <h1>Send an email</h1>
    <form action="/myaction" method="post">
        <fieldset>
            <label for="name">Name:</label>
            <input type="text" id="name" name="name" placeholder="Enter your full name" />

            <label for="email">Email:</label>
            <input type="email" id="email" placeholder="Enter your email address" />

            <label for="message">Message:</label>
            <textarea id="message" placeholder="What's on your mind?"></textarea>

            <input type="submit" value="Send message" />

        </fieldset>
    </form>
</div>
</body>
</html>

这是在服务器上运行的 node.js 函数:

var sys = require('sys'),
    http = require('http');
    http.createServer(function (req, res) {
            switch (req.url) 
                case '/myaction':
                        res.end(?????);
                    break;
            }
    }).listen(8080);
sys.puts('Server running at http://127.0.0.1:8080/');

我有两个问题:

  1. 如何从 html 页面调用 node.js 中的 myaction 函数?因为 html 文件在 80 端口上运行,node.js 在 8080 上运行(当我尝试将 node.js 移动到 80 端口时,它会写入“//Unhandled 'error' event”)
  2. 在 node.js 函数中我放了“??????”如何从 html 表单中获取数据。 当我输入 req.html.body.name 时,我没有得到数据...

最佳答案

使用 http.createServer 是非常低级的,对于按原样创建 Web 应用程序确实没有用处。

Express 是一个很好的框架,我强烈建议使用它。您可以使用 npm install express 安装它。

如果你有,你可以创建一个基本的应用程序来处理你的表单:

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

//Note that in version 4 of express, express.bodyParser() was
//deprecated in favor of a separate 'body-parser' module.
app.use(bodyParser.urlencoded({ extended: true })); 

//app.use(express.bodyParser());

app.post('/myaction', function(req, res) {
  res.send('You sent the name "' + req.body.name + '".');
});

app.listen(8080, function() {
  console.log('Server running at http://127.0.0.1:8080/');
});

您可以使用以下方法使您的表单指向它:

<form action="http://127.0.0.1:8080/myaction" method="post">

您不能在端口 80 上运行 Node 的原因是该端口上已经有一个进程正在运行(它正在为您的 index.html 提供服务)。您还可以使用 Express 来提供静态内容,例如 index.html,使用 express.static 中间件。

关于html - Node.js - 如何从 html 发送数据以表达,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15568851/

相关文章:

css - HTML - 复选框显示为黑色且 initial-scale=1.0

javascript - axios请求抛出未知错误

java - 如何通过 Android Studio 在我的应用程序中嵌入 google docs 表单?

javascript - 取消选中 Bootstrap 单选按钮

html - 我正在尝试定位图像,使其在不同的屏幕尺寸上具有相同的位置

html - 使用XPath选择包含特定类的表

javascript - 不要读取node.js中的JSON对象

php - 发布前离线保存数据

javascript - 防止使用直接 url 查看 css 和 js 文件

node.js - 如何使用 Node.js 在 MongoDB 中存储大量数字