这是 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/');
我有两个问题:
- 如何从 html 页面调用 node.js 中的
myaction
函数?因为 html 文件在 80 端口上运行,node.js 在 8080 上运行(当我尝试将 node.js 移动到 80 端口时,它会写入“//Unhandled 'error' event”) - 在 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/