Node.js framework project to build a combined Express

A brief

The project is node.jswritten back interfaces, front-end vue.jsimplementation of an online coffee isolated projects. This tutorial is a simple entry, continue to be updated on the late actual usage.

Second, build applications

1, through the application builder tool  express-generator can quickly create an application. Premise execute the following command in your terminal has been installed node.js. If not, install itself.

npm install -g cnpm --registry=https://registry.npm.taobao.org #安装淘宝镜像
npm install express-generator -g #全局安装生成器
express --view=ejs blog          #创建项目
cd blog      					#进入项目
cnpm i 					#安装node_modules

DEBUG=blog:* npm start    #启动项目

2, then open the browser  http://localhost:3000/ URL, you can see this app.

3, from the webstromopen project routesfolder inside index.js, try to modify the titleinside Express123, then refresh the page, the page and found no change. This time to be installed in accordance with the following command:

cnpm i nodemon -S

In package.jsonmodified as follows code file,

"scripts": {
  "start": "nodemon ./bin/www"
},

After the change, use the command npm startto restart the project, real-time monitoring test successfully!

Third, the basic use

1, configuration, installation database. SequelizeIs based on promisethe Node.js ORMcurrent support Postgres, MySQL, SQLiteand Microsoft SQL Serverit has a powerful transaction support, relationship, read and copy functions.
Reference Documenthttps://demopark.github.io/sequelize-docs-Zh-CN/

cnpm install --save sequelize   #安装数据库依赖包
cnpm install --save mysql2      #安装数据库
sequelize init                  #初始化,会创建对应项目的模型、迁移、种子文件等

#如果初始化失败,请执行下面命令,再初始化
npm install -g sequelize-cli

2, create a migration file and model:sequelize model:generate --name Article --attributes title:string,content:text

3, in the config/config.jsonfile, modify the database configuration.

Create your local database:sequelize db:create --charset 'utf8mb4'

[Image dump the chain fails, the source station may have security chain mechanism, it is recommended to save the picture down uploaded directly (img-ZwLi56h0-1584445559798) (https://images.itfun.tv/photo/2019/44c8f36ea2911db2557e2ae0303ebdfd.png-large )]

4, perform database migration:sequelize db:migrate

5. Create a seed file:sequelize seed:generate --name demo-article

6, after changing the seed file data, run seed file:sequelize db:seed:all

up: (queryInterface, Sequelize) => {
     return queryInterface.bulkInsert('Articles', [
        {
             title: '今天天气真好',
             content: '天气预报说虽然今天是晴天,可是明天会下雨。',
             createdAt: new Date(),
             updatedAt: new Date()
         },
         {
             title: '武汉什么早餐最好吃?',
             content: '毫无疑问是三鲜豆皮 + 热干面 + 米酒',
             createdAt: new Date(),
             updatedAt: new Date()
          }
     ], {});
},

NOTE: To view the database, you will find the newly inserted data in the time in question, when the server is not in the East eight districts, dealing with the problem area can sometimes be more trouble, especially when the client is Beijing time, the time difference with the server, then need to do treated as follows:

cnpm i china-time --save

In the seedersseed file folder, add the following code:

const chinaTime = require('china-time');

***

createdAt: chinaTime('YYYY-MM-DD HH:mm:ss'),

Go to seed file to run the command, problem solved! references:https://www.v2ex.com/t/429546

This method is more complex, we use a simple way to solve this problem. In config/config.jsonadd the following code file:

"timezone": "+08:00"

as the picture shows:

7, start the npm start project: . Look at the code you will find that this time, we have created a separate module articles.

In the app.jsfile registration route, as follows:

****
var articlesRouter = require('./routes/articles');

****
app.use('/articles', articlesRouter);

****

Open the articles.jsfile write the following code:

var express = require('express');
var router = express.Router();
var models = require('../models');

//文章列表
router.get('/', function (req, res, next) {
    models.Article.findAll({limit:2,order: [['id', 'DESC']]}).then(articles => {
        res.json({articles: articles});
    })
});


//文章详情
router.get('/:id', function (req, res, next) {
    let id = req.params.id;
    models.Article.findByPk(id).then(article => {
        res.json({article: article})
    })
});

// 新增文章
router.post('/', function (req, res, next) {
    //res.json(req.body)
     models.Article.create(req.body).then((article) => {
         res.json({article: article})
     });
});

// 编辑文章
router.put('/:id', function (req, res, next) {
    models.Article.findByPk(req.params.id).then(article => {
        article.update(req.body);
        res.json({article: article})
    })
});

// 删除
router.delete('/:id', function (req, res, next) {
    models.Article.findByPk(req.params.id).then(article => {
        article.destroy();
    })
});

module.exports = router;

Browser access: http://localhost:3000/articlesYou will find that I have to check the data have been found:

Published 14 original articles · won praise 1 · views 94

Guess you like

Origin blog.csdn.net/huangdj321/article/details/104929433