Node. js blog instance (6) message function, node. js instance
Original tutorial.
This function enables users to leave messages for articles. The messages are stored in the database.
Post. js, modify the document to be saved in Post. prototype. save as follows:
// Var post = {name: this. name, time: time, title: this. title, post: this. post, comments: []};
The comments key (array) is added to the document to store messages (objects) in this article ). To enable the message to support the markdown syntax, we set the following in the Post. getOne function:
Doc. post = markdown. toHTML (doc. post); changed:
// Parse markdown as html
if (doc) {doc.comments.forEach(function (comment) {comment.content = markdown.toHTML(comment.content);});}
Create a comment. js file under blog/models/and add the following code:
Var mongodb = require ('. /db'); function Comment (name, day, title, comment) {this. name = name; this. day = day; this. title = title; this. comment = comment;} module. exports = Comment; // stores Comment messages. prototype. save = function (callback) {var name = this. name, day = this. day, title = this. title, comment = this. comment; // open the database mongodb. open (function (err, db) {if (err) {return callback (err);} // read the posts set db. collection ('posts', function (err, collection) {if (err) {mongodb. close (); return callback (err);} // search for a document by user name, time, and title, and add a message object to the comments array of the document. update ({"name": name, "time. day ": day," title ": title}, {$ push: {" comments ": comment }}, function (err) {mongodb. close (); if (err) {return callback (err) ;}callback (null );});});});};
Modify index. js and add a line of code after Post = require ('../models/post. js:
Post=require('../models/post.js'), Comment=require('../models/comment.js');
Create a comment View File, create comment. ejs in the blog/views/folder, and add the following code:
<Br/> <% post. comments. forEach (function (comment, index) {%> <p> <a href = "<%= comment. website %> "> <% = comment. name %> </a> <span class = "info"> replied to <% = comment. time %> </span> </p> <%-comment. content %> </p> <%}) %> <form method = "post"> <% if (user) {%> Name: <input type = "text" name = "name" value = "<% = user. name %> "/> <br/> email: <input type =" text "name =" email "value =" <% = user. email %> "/> <br/> URL: <input type =" text "name =" website "value ="/u/<% = user. name %> "/> <br/> <%} else {%> name: <input type =" text "name =" name "/> <br/> Email: <input type = "text" name = "email"/> <br/> URL: <input type = "text" name = "website" value = "http: // "/> <br/> <% }%> <textarea name =" content "rows =" 5 "cols =" 80 "> </textarea> <br/> <input type = "submit" value = "message"/> </form>
Note: Different prompts are displayed based on the user logon status. Note that when an Unlogged-on user leaves a message, the website must be prefixed with http, otherwise, the connection is generated based on the current url (localhost: 3000 ).
Open article. ejs and add a line of code before <%-include footer %>:
<%- include comment %>
In this way, the message module is introduced on the article page.
Add code for index. js:
App. post ('/u/: name/: day/: title', function (req, res) {var date = new Date (), time = date. getFullYear () + "-" + (date. getMonth () + 1) + "-" + date. getDate () + "" + date. getHours () + ":" + (date. getMinutes () <10? '0' + date. getMinutes (): date. getMinutes (); var comment = {name: req. body. name, email: req. body. email, website: req. body. website, time: time, content: req. body. content}; var newComment = new Comment (req. params. name, req. params. day, req. params. title, comment); newComment. save (function (err) {if (err) {req. flash ('error', err); return res. redirect ('back');} req. flash ('success', 'message successful! '); Res. redirect ('back ');});});
Use res. redirect ('back'); to return to this article page after the message is successfully sent.
See the results:
Log on to your blog and post an article for testing:
Click to enter the article to view the message section and leave a comment:
The message is sent successfully. Click again to enter the article to view the message:
Note: Before testing, you can clear the content in the mongodb/blog folder to avoid problems.
Nodejs can be used to implement a simple interface server.
Var http = require ('http'); var mysql = require ('mysql'); var connection = mysql. createConnection ({host: 'localhost', user: 'me', password: 'secret',}); // start your mysql connection. connect (); var server = http. createServer (function (req, res) {// if you send a GET request to 127.0.0.1: 1337/test? Var url_info = require ('url') If a = 1 & B = 2 '). parse (req. url, true); // check whether requestif (url_info.pathname = '/test') for/test {// use url encode for query, in this way, you can use post to send var post_data = require ('querystring '). stringify (url_info.query); // optionvar post_options of post = {host: 'localhost', port: 1337, path: '/response_logic', method: 'post', headers: {'content-type': 'application/x-www-form-urlencoded ', 'content-length': post_data.length}; // issue the postvar request_made = http. request (post_options, function (response_received) {var buf_list = new Array (); response_received.on ('data', function (data) {buf_list.push (data );}); response_received.on ('end', function () {var response_body = Buffer. concat (buf_list); res. end (response_body); connection. query ('insert ......... ', function (err, rows, fields) {// process your result}) ;}); // send the post's datare ...... remaining full text>
In the example of creating a microblog in the nodejs Development Guide, an error is reported during the process of creating a registered account.
It is setting. js, a js written by myself for storing the database configuration file. This is not a module written by others. It is a self-created seting. js file with the content of a json
Moudule. exports = {
CookieSecret: 'microblogbyvoid ',
Db: 'microblog ',
Host: 'localhost'
}
See P109 in node. js Development Guide.
References: node. js Development Guide