Home  >  Article  >  Web Front-end  >  nodejs tutorial to create a simple article publishing system_node.js

nodejs tutorial to create a simple article publishing system_node.js

WBOY
WBOYOriginal
2016-05-16 16:30:431714browse

Foreword

We will make a simple news release system today. The first stage of the system does not need to be too difficult. It mainly has the following functions

① News type management

② News management (with image upload function)

③ News browsing

Although there are not many functions, it also covers many basic operations. The program only adds, deletes, checks, and uploads attachments, which is enough. So let’s start our study today

Preparation

After yesterday’s troubles, we already have nodeJS and mongoDB environments. Now we can directly create new project files and database files

The first step is to open the command prompt and switch to the D drive and enter

Copy code The code is as follows:
D:>express -e news

Then the system will automatically build the basic environment happily

Obviously, many module dependencies are not there. At this time, just take the test of yesterday’s package.json:

Copy code The code is as follows:

{
"name": "application-name",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "node app.js"
},
"dependencies": {
"express": "3.4.8",
"ejs": "*",
"mongodb": "*"
}
}

Then switch to the project directory:

Copy code The code is as follows:
nmp install

After all the dependent files are downloaded, we enter

Copy code The code is as follows:

D:news>node app
Express server listening on port 3000

So, our program ran happily. When we opened the URL, we found that there was indeed no problem

PS: There is a problem that needs attention here. The file we downloaded is not UTF-8 encoded, so the Chinese may be garbled. The file encoding needs to be unified by yourself

When the program is running, database-related configuration is required

① First create a new news folder in the mongoDB directory

② Add configuration file settings.js to the project

Copy code The code is as follows:

module.exports = {
cookieSecret: 'myNews',
db: 'news',
host: 'localhost'
};

③ Create a new models directory and create a new db.js

Copy code The code is as follows:

var settings = require('../settings'),
Db = require('mongodb').Db,
Connection = require('mongodb').Connection,
Server = require('mongodb').Server;
module.exports = new Db(settings.db, new Server(settings.host, Connection.DEFAULT_PORT), { safe: true });

④ Create a new news.bat program on the desktop

Copy code The code is as follows:
d:mongodbbinmongod.exe -dbpath d:mongodbnews

To start the database in the future, we only need to run it. In this way, our preliminary preparations are basically completed

But there are two annoying things here. One is that it is annoying to start the news program every time, and the other is that you need to restart to modify anything, so we will solve these two problems here first

① Create new news_app.bat on the desktop and run it later to start the program

Copy code The code is as follows:
node d:newsapp

② Supervisor is a process protection program. We can use him to help us restart the program. First follow, and then adjust our node_app.bat

Copy code The code is as follows:
supervisor d:newsapp

Of course you need to install it before:

Copy code The code is as follows:
npm install -g supervisor

After this, there is no need to manually restart after modifying the file (news_app needs to be placed in the project directory), so the preparation work ends here

Project Structure

After the first step, we need to think about the project structure

① The home page is index, where all news types and news items will be listed

② Each news item has three buttons: edit/delete/view

③ The homepage has a button to add news (you can upload pictures when adding)

Basic functions are as above

So, we removed the routing function in the app and put all the routes in the index

Copy code The code is as follows:

//Put the routing function into index
//app.get('/', routes.index);
//app.get('/users', user.list);
routes(app);

Copy code The code is as follows:

module.exports = function (app) {
//Homepage, now also the homepage
app.get('/', function (req, res) {
res.render('index', { title: 'Express' });
});
app.get('/add', function (req, res) {
res.send('Add news request');
});
app.get('/delete', function (req, res) {
res.send('Delete news request');
});
app.get('/view', function (req, res) {
res.send('View news request');
});
app.get('/update', function (req, res) {
res.send('Modify news request');
});
};

The first step is as simple as this, because adding news should have a separate page, and clicking the add button will have other processing, so each request must be broken down internally. The current regulations are as follows:

/ Default page, which displays all genres and news, with a delete button

/add Enter the add news page

/addNews Add news specific post request address (response when clicking the button)

/delete Delete news request

/view specific news query

So I slightly modified the above route:

Copy code The code is as follows:

module.exports = function (app) {
//Homepage, now also the homepage
app.get('/', function (req, res) {
res.render('index', { title: 'Express' });
});
app.get('/add', function (req, res) {
res.send('Add news page');
});
app.post('/addNews', function (req, res) {
res.send('Processing request to add news');
});
app.get('/delete', function (req, res) {
res.send('Delete news request');
});
app.get('/view', function (req, res) {
res.send('View news request');
});
};

So we need to create several new templates to organize our web pages. Here we do not separate the head and tail, just the simplest page

Added two template files, add and view, which temporarily behave the same as index.ejs, and modified navigation

Copy code The code is as follows:

module.exports = function (app) {
//Homepage, now also the homepage
app.get('/', function (req, res) {
res.render('index', { title: 'Express' });
});
app.get('/add', function (req, res) {
res.render('add', { title: 'Add news page' });
});
app.post('/addNews', function (req, res) {
res.send('Processing request to add news');
});
app.get('/delete', function (req, res) {
res.send('Delete news request');
});
app.get('/view', function (req, res) {
res.render('view', { title: 'View News Request' });
});
};

This is the end of the project structure

Data Operation

After the overall structure is out, we need to perform data operations:

① Add data (add news)

② Display data (display news)

③ Delete data (delete news)

Originally, it also involved type operations, but I couldn’t figure it out while doing it. I’ll leave it alone for the time being, because it’s easy to get confused when doing it for the first time

Add news

Here, we don’t use form submission, we use ajax... Here we introduce the zepto library, so our page becomes like this

Copy code The code is as follows:




<br>                                                                                                             <link rel='stylesheet' href='/stylesheets/style.css' /><br> <script src="javascripts/zepto.js" type="text/javascript"></script><br> </head><br> <body><br> <h1><br>                                                                                         <div><br> Title:<input type="text" id="title" /><br> </div><br> <div><br> Content:<textarea id="content"></textarea><br> </div><br> <div><br>            <input type="button" type="button" id="ok" value="Add News" /><br> </div><br> <script type="text/javascript"><br>            $(document).ready(function () {<br>                 $('#ok').click(function () {<br>               var param = {};<br>                    param.title = $('#title').val();<br>                     param.content = $('#content').val();<br>                         $.post('/addNews', param, function () {<br> console.log('Added successfully');<br>                 });<br>             });<br>         });<br> </script><br> </body><br> </html><br> <br><br> </div> <p><img alt="" src="http://files.jb51.net/file_images/article/201411/2014112114583352.png"> <img alt="" src="http://files.jb51.net/file_images/article/201411/2014112114583353.png">Although there is no request response program yet, so the data will not be processed, and we do not have attachments here (only one attachment is allowed now), so we modify the code and add pictures: </p> <p>PS: The more troublesome thing is that the ajax processing of the image is a bit troublesome, so we just change back to the form operation, otherwise it will take a long time...</p> <p></p> <p></p> <div class="codetitle"><span>Copy code<a style="CURSOR: pointer" data="79067" class="copybut" id="copybut79067" onclick="doCopy('code79067')"><u></u> The code is as follows:</a><div class="codebody" id="code79067"> <br> <html><br> <head><br>     <title><br>         <%= title %>
   


   


        <%= title %>


   

   

        标题:
   

   

        图片:
   

   

        内容:
   

   

       
   

   



这个样子就不需要过多的考虑附件问题,先暂时如此吧,现在先处理请求程序,这里先在public里面新建news文件夹用于存储其图片

model

在models文件夹新增news.js文件,为其构建实体,并赋予新增查询相关操作:

复制代码 代码如下:

var mongodb = require('./db');

function News(title, content, pic) {
  this.title = title;
  this.content = content;
  this.pic = pic;//保存存储路径
};
module.exports = News;
//存储数据
News.prototype = {
  save: function (callback) {
    var date = new Date();
    var time = {
      date: date,
      year: date.getFullYear(),
      month: date.getFullYear() "-" (date.getMonth() 1),
      day: date.getFullYear() "-" (date.getMonth() 1) "-" date.getDate(),
      minute: date.getFullYear() "-" (date.getMonth() 1) "-" date.getDate() " "
      date.getHours() ":" (date.getMinutes() < 10 ? '0' date.getMinutes() : date.getMinutes())
    }
    //数据存储对象
    var news = {
      title: this.title,
      content: this.content,
      pic: this.pic, //图片处理最后来说,现在先乱存
      time: time
    };
    //打开数据连接,打开就是一个回调......
    mongodb.open(function (err, db) {
      //错误就退出
      if (err) {
        return callback(err);
      }
      //打开news集合
      db.collection('news', function (err, collection) {
        if (err) {
          mongodb.close();
          return callback(err);
        }
        //写入集合(写入数据库)
        collection.insert(news, { safe: true }, function (err) {
          return callback(err);
        });
        callback(null);//err为null
      });
    });
  }
};

So, the program to write to the database is there. Here we try to see if we can insert it into the database. Of course, we need to modify the routing program

PS: Of course you cannot write too much logic code in the routing department. This file will have to be separated in the future

At this time, the logic in /addNews needs to be changed

Copy code The code is as follows:

app.post('/addNews', function (req, res) {
var title = req.body.title;
var content = req.body.content;
var pic = req.body.pic;
var news = new News(title, content, pic)
news.save(function (err, data) {
res.send(data);
})
});

After checking, the problem is not big. What needs to be solved now is the attachment problem

Upload pictures

Express itself supports the image upload function. Express parses the request body through bodyParser, and then uploads files through it. It uses formidable

internally.

Here, change app.use(express.bodyParser()) in app.js to:

Copy code The code is as follows:
app.use(express.bodyParser({ keepExtensions: true, uploadDir: './public/news' }));

Open index.js and add a line of code in front:

Copy code The code is as follows:
fs = require('fs'),

Modify the index file:

Copy code The code is as follows:

app.post('/addNews', function (req, res) {
for (var i in req.files) {
If (req.files[i] == 0) {
//Delete a file synchronously
         fs.unlinkSync(req.files[i].path);
console.log('success removed an empty file');
} else {
var path = './public/news/' req.files[i].name;
//Rename a file using synchronous method
          fs.renameSync(req.files[i].path, path);
console.log('suncess renamed a file');
}
}
// var title = req.body.title;
// var content = req.body.content;
// var pic = req.body.pic;
// var news = new News(title, content, pic)
// news.save(function (err, data) {
// res.send(data);
// })
});

At this time, select the file and click Add News, and our file will be uploaded

At this time, I only need to record the file name in the database, and there will be pictures in the file directory

Copy code The code is as follows:

app.post('/addNews', function (req, res) {
var pic = null;
for (var i in req.files) {
If (req.files[i] == 0) {
//Delete a file synchronously
         fs.unlinkSync(req.files[i].path);
console.log('success removed an empty file');
} else {
var path = './public/news/' req.files[i].name;
//Rename a file using synchronous method
          fs.renameSync(req.files[i].path, path);
console.log('suncess renamed a file');
}
Pic = req.files[i].name;
}
var title = req.body.title;
var content = req.body.content;
var news = new News(title, content, pic)
news.save(function (err, data) {
res.send(data);
})
res.send('Request successful, return to home page');
});

There is data in the database and there are files in our directory. Now we just need to read the data out

PS: Brothers are urging me to go out for a drink during the holiday

Read data

The second step is of course to read the data. The first is to read the data on the home page:

Copy code The code is as follows:

var mongodb = require('./db');
function News(title, content, pic) {
this.title = title;
this.content = content;
this.pic = pic;//Save storage path
};
module.exports = News;
//Storage data
News.prototype = {
save: function (callback) {
var date = new Date();
//Data storage object
var news = {
title: this.title,
Content: this.content,
Pic: this.pic, //Finally, image processing, now save it randomly
date: date
};
//Open the data connection, opening is a callback...
mongodb.open(function (err, db) {
//Exit if error occurs
If (err) {
         return callback(err);
}
//Open the news collection
db.collection('news', function (err, collection) {
If (err) {
             mongodb.close();
            return callback(err);
}
//Write collection (write to database)
         collection.insert(news, { safe: true }, function (err) {
            return callback(err);
        });
​​​​ callback(null); //err is null
});
});
}
};
//Read the article and its related information
News.get = function (id, callback) {
//Open database
mongodb.open(function (err, db) {
If (err) {
Return callback(err);
}
db.collection('news', function (err, collection) {
If (err) {
          mongodb.close();
         return callback(err);
}
var query = {};
If (id) {
​​​​ query.id = id;
}
//Query articles based on query object
Collection.find(query).sort({
date: -1
}).toArray(function (err, data) {
          mongodb.close();
If (err) {
             return callback(err); //Failed! Return err
}
​​​​ callback(null, data); //Success! Return the results of the query in the form of an array
});
});
});
};
news.js

Copy code The code is as follows:




    <br>         <%= title %>
   


   


        <%= title %>


   

            <%for(var k in data) { %>
           

  •            

                   标题: <%=data[k].title %>

               

                  内容:  <%=data[k].content%>

                 

                  附件:

                 

             

              删除
             

             

       
        <%} %>
   


结语

好了,文章发布系统的制作就先到这里了,以后我们再慢慢增加功能,慢慢做美化。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:Javascript study notes: Array traversal and length attribute_Basic knowledgeNext article:Javascript study notes: Array traversal and length attribute_Basic knowledge

Related articles

See more