[英]Node.js - How to send data from html to express
这是 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/');
我有两个问题:
myaction
函数? 因为 html 文件在端口 80 和 node.js 上运行在 8080(当我尝试将 node.js 移动到端口 80 时,它会写入“// Unhandled 'error' event”)使用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
中间件。
我想扩展Obertklep的答案。 在他的示例中,它是一个名为body-parser
的 NPM 模块,它完成了大部分工作。 他放req.body.name
,我相信他/她正在使用body-parser
来获取提交表单时收到的 name 属性的内容。
如果您不想使用 Express,请使用内置 Node 模块的querystring
。 有关如何使用querystring
的示例,请参阅以下链接中的答案。
查看这个答案可能会有所帮助,它与您的任务非常相似。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.