Node. js blog instance (7) Paging function, node. js Paging

Source: Internet
Author: User

Node. js blog instance (7) Paging function, node. js Paging

Original tutorial.

Adds the paging function to the homepage and user pages of a blog. Set: up to 10 articles can be displayed on each page of the home page and user page.
Here the skip and limit operations of mongodb are used.
Open post. js and modify the Post. getAll function as follows:

// Read the article and its related information Post. getTen = function (name, page, callback) {// 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);} var query ={}; if (name) {query. name = name;} // use count to return the number of documents in a specific query. count (query, function (err, total) {// query by query object, and skip the first (page-1) * 10 results, return 10 result collections after the return. find (query, {skip :( page-1) * 10, limit: 10 }). sort ({time:-1 }). toArray (function (err, docs) {mongodb. close (); if (err) {return callback (err); // failed! Returns err} // parses markdown to htmldocs. forEach (function (doc) {doc. post = markdown. toHTML (doc. post) ;}); callback (null, docs, total); // success! Returns the query result in the form of an array });});});});};
Open index. js and modify app. get ('/', function (req, res) {as follows:
<Span style = "white-space: pre"> </span> app. get ('/', function (req, res) {// checks whether it is the first page, and converts the requested page number to number type var page = req. query. p? ParseInt (req. query. p): 1; // query and return the 10 articles Post on the page. getTen (null, page, function (err, posts, total) {if (err) {posts = [];} res. render ('index', {title: 'homepage', page: page, isFirstPage: (page-1) = 0, isLastPage: (page-1) * 10 + posts. length) = total, user: req. session. user, posts: posts, success: req. flash ('success '). toString (), error: req. flash ('error '). toString ()});});});
Note: The number of pages obtained through req. query. p is a string. We need to convert it to a number through parseInt () for later use. Change Post. getAll to Post. getTen.
Modify app. get ('/u/: name') in index. js as follows:

<Span style = "white-space: pre"> </span> app. get ('/u/: name', function (req, res) {var page = req. query. p? ParseInt (req. query. p): 1; // check whether the User has user. get (req. params. name, function (err, User) {if (! User) {req. flash ('error', 'user does not exist! '); Return res. redirect ('/'); // jump to the homepage if the user does not exist} // query and return the 10 Post articles on the page of the user. getTen (user. name, page, function (err, posts, total) {if (err) {req. flash ('error', err); return res. redirect ('/');} res. render ('user', {title: user. name, posts: posts, page: page, isFirstPage: (page-1) = 0, isLastPage: (page-1) * 10 + posts. length) = total, user: req. session. user, success: req. flash ('success '). toString (), error: req. flash ('error '). toString ()});});});});
Create paging. ejs in the blog/views/folder and add the following code:
<Br/> <div> <% if (! IsFirstPage) {%> <span class = "prepage"> <a title = "Previous Page" href = "? P = <% = page-1%> "> previous page </a> </span> <% }%> <% if (! IsLastPage) {%> <span class = "nextpage"> <a title = "next page" href = "? P = <% = page + 1%> "> next page </a> </span> <% }%> </div>
If (! IsFirstPage) determines whether it is the first page. if it is not the first page, the "Previous Page" is displayed. if (! IsLastPage) determines whether it is the last page. If it is not the last page, the next page is displayed ".
Next, we will introduce pagination on the home page and user page. Modify index. ejs and user. ejs, and add a line of code before <%-include footer %>:
<%- include paging %>
Add the following style to style.css:
.prepage a{float:left;text-decoration:none;padding:.5em 1em;color:#ff0000;font-weight:bold;}.nextpage a{float:right;text-decoration:none;padding:.5em 1em;color:#ff0000;font-weight:bold;}.prepage a:hover,.nextpage a:hover{text-decoration:none;background-color:#ff0000;color:#f9f9f9;-webkit-transition:color .2s linear;}
Effect:

11 articles published above =

Click Next page


The ghost code requires more activity and more water.



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

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>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.