【发布时间】:2014-11-16 19:16:52
【问题描述】:
我正在创建一个博客作为学习练习 - 请参阅 github project - 在 node.js 中从头开始。我有一个带有input 和textarea 字段的html 表单。在提交时,每个都应该分别被解析为title 和content。
<!DOCTYPE html>
<html>
<head>
<title>
Post Form
</title>
<link href="/css/master.css" rel="stylesheet" type="text/css" />
</head>
<body>
<h1>
New post
</h1>
<form method="post" action="/posts" id="new_post" class="new_post">
<div class="field">
<label for="post_title">Title</label><br>
<input type="text" name="title" id="post_title" size="30" />
</div>
<div class="field">
<label for="post_content">Content</label><br>
<textarea name="content" cols="40" rows="20" id="post_content"></textarea>
</div>
<div class="actions">
<input type="submit" value="Create Post" id="post_submit" />
</div>
</form>
<p><br>
<a href="/home">Back</a>
</p>
</body>
</html>
在一个 index.js 文件中,我定义了路由和一些实用函数来帮助我从提交的信息中解析数据。
var http = require('http'),
url = require('url'),
fs = require('fs'),
qs = require('querystring');
// html file cache
var homeHTML = fs.readFileSync('views/post/home.html');
var newHTML = fs.readFileSync('views/post/new.html');
var postsHTML = fs.readFileSync('views/post/posts.html')
// render functions
...
function renderPostForm(request, response) {
response.writeHead(200, {
'content-type': 'text/html; charset=utf-8'
});
response.end(newHTML);
}
function addNewPost(request, response) {
response.writeHead(200, {
'content-type': 'text/html; charset=utf-8'
});
// the parseBody is defined below this function
// title and content should get logged to the console, but title comes out Title: undefined
// content works fine
parseBody(request, function(body) {
var post = {
title: body.title,
content: body.content
}
console.log("Title: " + post.title);
console.log("Content: " + post.content);
});
response.end(postsHTML);
}
// utils
...
function parseBody(request, callback) {
var body = " ";
request.on('data', function(chunk) {
body += chunk;
});
request.on('end', function() {
callback(qs.parse(body)); // I may be misunderstanding the usage of the parse function
});
}
// routes
var homeREGEX = new RegExp('^/?$');
var newREGEX = new RegExp('^/posts/new/?$');
var postsREGEX = new RegExp('^/posts/?$');
// server
var server = http.createServer(function(request, response){
var pathname = url.parse(request.url).pathname;
if (homeREGEX.test(pathname)) {
renderHome(request, response);
} else if (newREGEX.test(pathname)) {
renderPostForm(request, response);
} else if (postsREGEX.test(pathname)) {
addNewPost(request, response);
} else {
render404(request, response);
}
});
server.listen(3000);
【问题讨论】:
-
您认为您的表单数据应该在代码的哪个位置进行解析?发布请求不会作为 URL 查询字符串参数发送。 Post 数据在请求正文中发送,需要从那里解析。
-
好吧,我定义了
parseBody函数,它从body上的querystring模块(在顶部导入)调用qs.parse函数。它在所有数据都从请求中分块后执行此操作。它在 addNewPost 函数中被调用,创建一个名为“post”的新对象,并用body.title和body.content填充它。显然,body.content被解析没有问题。为什么不body.title?所以要回答你的问题,在addNewPost函数中通过parseBody函数。
标签: html node.js parsing web-applications user-input