Blog: blog.csdn.net/bluebluesky…

NPM install ----- Rely on NPM run dev ----- run NPM run build ----- pack node prod.server.js ----- Pack and run // remember to replace Vue and chat. vue IO. Connect ('http://qiufengh.com:8081') http://qiufengh.com:8081 change your project address.Copy the code

Watch online at www.qiufengh.com:8081/#/

After imitating netease cloud music with Vuejs in the last project (realizing the function of listening to songs and searching), I found that it was very confusing to use vue model to manage the last project. Then I went to see Vuex, planning to practice my skills in a project instead of repeating a project. This time, I gave up my appearance level and decided to follow my heart. A real-time chat system is developed by combining nodeJS and mongodb database. This system can be said to be unified, but also realize a front-end programmer’s dream, before and after all. I think of myself as a complete project. Project address: github.com/hua1995116/… If you feel good, please send a star.

Realize the function

  • Chat function – done
  • Multiple chat rooms — done
  • Docking with robot — done
  • Picture sending — done
  • Registration function – done
  • Login feature – done

Technology stack

  • Front-end VUE, VUE-Router,vuex
  • Back-end NodeJS, Express
  • Mongo database
  • Communication websocket
  • Scaffolding tool VUE-CLI

structure

├ ─ build ├ ─ config ├ ─ models (storing mongoose object) ├ ─ schemas (deposit mongoose schemas model) ├ ─ SRC │ │ App. Vue │ │ main. Js (main entrance) │ ├ ─ assets │ ├ ─ components (component) │ ├ ─ the router (vue – the router routing) │ └ ─ store (vuex) └ ─ the static resources (static)

Start by building a project with the scaffolding tool. Like this:

vue init webpack my-project-name
Copy the code

It looks something like this

Good! Since this is a combat project, I won’t go into these configuration issues. Or else we’re going off topic. Or I’ll be beaten up by my little brothers and sisters.

The front end

First look at the page layout in the SRC directory. The main js / / the main entry

Import Vue from 'Vue' import App from './App' import router from './router' import store from './store' // Use museui import MuseUI from 'muse-ui' import 'muse-ui/dist/muse-ui.css' Vue.use(MuseUI) Vue.config.productionTip = false /* eslint-disable no-new */ new Vue({ el: '#app', router, store, template: '<App/>', components: {App} })Copy the code

We chose muse-UI to make the whole project look nice, and the UI framework is really beautiful. Look at muse-UI if you don’t believe me. The rest is the scaffolding’s default configuration.

route/router.js

import Vue from 'vue'
import Router from 'vue-router'
import Index from '@/components/Index'
import Robot from '@/components/Robot'
import Home from '@/components/Home'

Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/',
      name: 'Index',
      component: Index
    },
    {
      path: '/robot',
      name: 'Robot',
      component: Robot
    },
    {
      path: '/home',
      name: 'Home',
      component: Home
    }
  ]
})
Copy the code

As you can see, there are three routes. Yes, we have three routes. The first is the chat room with you, and the second is the chat room with our lovely Baymax, our Turing robot. You can do one of your own sometime. The third piece is our personal center, although there is nothing in this piece. But after all good-looking, oh ~ forget, we are heart, how can only look at the face.

components/Chat.vue

created() {
    const that = this
    this.socket = io.connect('http://qiufengh.com:8081')
    this.socket.on('message', function(obj) {
        that.$store.commit('addroomdetailinfos', obj)
        window.scrollTo(0, 900000)
    })
    this.socket.on('logout', function (obj) {
        that.$store.commit('setusers', obj)
    })
},
Copy the code
this.socket = io.connect('http://qiufengh.com:8081')
Copy the code

This sentence is mainly used to connect your current service, when downloading the next project, remember to change your service and port. Since both Index and Chat have Settings, you need to change connect to your own service in both index. vue and Chat. Socket.on () is used to receive messages. Socket.emit () is used to send messages. IO socket. IO socket. IO socket. This allows you to interact with the server. We’ll talk about the server side later.

store/index.js

State: {/ / stored user user: {name: "', SRC: '}, / / deposit history messhistory: {infos: []}, / / storage room information, in order to facilitate later do much room roomdetail: {id: [{message: 'Hi~ ', user: 'robot'}], // display chattoggle: False, // login page display control logintoggle: false, // register page display control registertoggle: true, // prompt box display control dialog: false, // prompt box content dialogInfo: "}Copy the code

Because control code too much, so after the content please move, my Github address. Github.com/hua1995116/…

The server side

The webpack code in build dev-server.js is too much and too messy to be easy to explain. Let’s focus on the server side for packaging. The codes are the same. Prod.server.js (root)

var express = require('express'); var config = require('./config/index'); var port = process.env.PORT || config.dev.port; var app = express(); var router = express.Router(); Router.get ('/',function(req,res,next){req.url = './index.html'; next(); }); app.use(router); Var Morgan = require(' Morgan ') var Morgan = require(' Morgan ') var Morgan = require(' Morgan ') //sesstion store var bodyParser = require('body-parser') var cookieParser = require('cookie-parser') var session = // Mongoose.Promise = require('bluebird') global.db = Mongoose. Connect (" mongo: / / localhost: 27017 / vuechat ") / / server json data submitted the app. Use (bodyParser. Json ()) App.use (bodyParser. Urlencoded ({extended: true})) // Sesstion store app.use(cookieParser()) app.use(session({secret:)) 'vuechat', resave: false, saveUninitialized: true })) var env = process.env.NODE_ENV || 'development' if ('development' === app.get('env')) { app.set('showStackError', true) app.use(morgan(':method :url :status')) app.locals.pretty = true mongoose.set('debug', true) } var server = app.listen(port) //websocket // var http = require('http').Server(app); var io = require('socket.io')(server); var Message = require('./models/message') var users = {} io.on('connection', Socket. On ('message', function (obj) {// Broadcast messages to all clients IO. obj) var mess = { username: obj.username, src:obj.src, msg: Obj. MSG, roomID :'room1'} var message = new Message(mess) Mess) {if (err) {console.log(err)} console.log(mess)}) console.log(obj.username + 'says: '+ obj.msg)}) socket. On ('login',function (obj) {users[obj.name] = obj // Users)}) socket.on('logout',function (name) {delete users[name] IO. Users)})}) / / declare static resource address app. Use (express. Static ('. / dist '));Copy the code

Schema models

schema/user.js

Var bcrypt = require('bcryptjs') var SALT_WORK_FACTOR = 10 var UserSchema = new mongoose.Schema({ name: { unique: true, type: String }, password: String, src: String, meta: { createAt: { type: Date, default: Date.now() }, updateAt: { type: Date, default: Date.now() } } }); Userschema. pre('save', function (next) { var user = this if (this.isNew) { this.createAt = this.updateAt = Date.now() } else { this.updateAt = Date.now() } bcrypt.genSalt(SALT_WORK_FACTOR, function (err, salt) { if (err) return next(err) bcrypt.hash(user.password, salt, function (err, Hash) {if (err) return next(err) user.password = hash next()})})}) // Used to compare passwords userschema.methods = { comparePassword: function (_password, cb) { bcrypt.compare(_password, this.password, function (err, isMatch) { if (err) return cb(err) cb(null, isMatch) }) } } UserSchema.statics = { fetch: function (cb) { return this .find({}) .sort('meta.updateAt') .exec(cb) }, findById: function (id, cb) { return this .findOne({_id: id}) .exec(cb) } } module.exports = UserSchemaCopy the code

Here the main use of an MD5 module, you can see bcryptjs

schema/message.js

Var MessageSchema = new mongoose.Schema({username: String, src:String, msg: String, roomid:String, time: { type: Date, default: Date.now()}}) // Static method messageschema. statics = {fetch: function (cb) { return this .find({}) .sort('time') .exec(cb) }, findById: function (id, cb) { return this .findOne({_id: id}) .exec(cb) } } module.exports = MessageSchemaCopy the code

The routes config/routes.js file of the server is a registered file

App. post('/user/signup', function (req, res) {var _user = req.body console.log(_user) user.findone ({name: _user.name}, function (err, user) { if (err) { console.log(err) } if (user) { res.json({ errno: 1, data: })} else {var user = new user (_user) user.save(function (err, {{user) if (err). The console log (err)} res. Json ({errno: 0, data: 'registration'})})}})})Copy the code

This function is used to verify whether the user name is the same.

So much for the core. Other specific please check my github address (with detailed notes, do not understand can ask, need to improve the seniors pointed out) : address: github.com/hua1995116/… Online viewing address: www.qiufengh.com:8081/#/

NPM install ----- Rely on NPM run dev ----- run NPM run build ----- pack node prod.server.js ----- Pack and run // remember to replace Vue and chat. vue IO. Connect ('http://qiufengh.com:8081') http://qiufengh.com:8081 change your project address.Copy the code

Last couple of pictures.