[英]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.