Я делаю блог как учебное упражнение - см. github project - с нуля в node.js. У меня есть html-форма, которая выглядит так: input
и поля textarea
. В представлении, каждый из них должен быть проанализирован как title
и content
, соответственно.Почему данные html-формы не корректно обрабатываются в приложении node.js?
<!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-адреса. Почтовые данные отправляются в тело запроса и требуют от него синтаксического анализа. – jfriend00
ну, я определил функцию parseBody, которая вызывает функцию qs.parse из модуля 'querystring' (импортированного вверху) на теле. Он делает это после того, как все данные переданы из запроса. Он вызывается в функции addNewPost, которая создает новый объект, называемый «post», заполняя его «body.title» и «body.content». Очевидно, что 'body.content' обрабатывается без проблем. Почему не 'body.title'? Поэтому, чтобы ответить на ваш вопрос, в функции 'addNewPost' через функцию' parseBody'. – kurofune