如何构建MEAN stack和socket.io应用程序的结构?

时间:2018-09-16 08:20:45

标签: angularjs node.js socket.io

我已经使用MEAN堆栈和http构建了一个简单的应用程序进行路由。

app.js

require('./db/dbConnection.js');
let express = require('express');
let app = express();
let path = require('path');
let bodyParser = require('body-parser');
let router = require('./server/routes');

app.set('port',3000);
app.use(express.static(path.join(__dirname, 'public'))); //this will auto look for index.html file in public folder and load (localhost:3000)
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json()); //to handle the data send by angular (data angular sent is in json format)
app.use('/server',router);
app.use('/node_module', express.static(__dirname + '/node_modules'));
app.use(function(req, res, next) {
    console.log(req.method, req.url);
    next();
});

let server = app.listen(app.get('port'), function() {
    let port = server.address().port;
    console.log("Magic happens on port " + port);
});

controller.js

 vm.login = function(){
    if(vm.username && vm.password){
        let user = {
            username: vm.username,
            password: vm.password
        };

        $http.post('server/user/login',user).then(
            returnedData => {
            //do smth
        });
    }

};

index.js(路由器)

let express = require('express');
let router = express.Router();

let ctrlUser = require('../controllers/svrUser.js');

router
    .route('/user/login')
    .post(ctrlUser.login);

module.exports = router;

svrUser.js

let mongoose = require('mongoose');
let user = mongoose.model('User');
let bcrypt = require('bcrypt-nodejs');
let jwt = require('jsonwebtoken');

var userController = {
    login: function(req, res){
        let searchObj = {
            username: req.body.username,
        };

        return user.findOne(searchObj).then(
            userDetail => {
            if(userDetail && (bcrypt.compareSync(req.body.password, userDetail.password))){
                let token = jwt.sign({username: userDetail.username}, 's3cr3t', {expiresIn: 3600});
                res.status(200).json({success: true, token: token});
            }else{
                res.status(400).json('Invalid username or password.');
            }
        })
    },
};

module.exports = userController;

这有效。现在我试图将socket.io应用于它,并且我坚持使用app.js。有没有人知道我应该对路由器做什么?

应用SOCKET.IO后

app.js

require('./db/dbConnection.js');
let express = require('express');
let app = express();
let path = require('path');
let bodyParser = require('body-parser');
let router = require('./server/routes');

let http = require('http').Server(app);
let io = require('socket.io')(http);

app.set('port',3000);
app.use(express.static(path.join(__dirname, 'public'))); //this will auto look for index.html file in public folder and load (localhost:3000)
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json()); //to handle the data send by angular (data angular sent is in json format)
app.use('/server',router);
app.use('/node_module', express.static(__dirname + '/node_modules'));
app.use(function(req, res, next) {
    console.log(req.method, req.url);
    next();
});

io.on('connection', function(socket){
    console.log("Socket connection has been established.")
    socket.on('sendToServer', function(param){
        console.log('back end receive websocket')
        socket.emit('test send', "WAHAHA");
    })

});

http.listen(3000, function(){
    console.log('Listening on *: 3000');
});

controller.js

angular.module('myApp').controller("LoginController", LoginController);

function LoginController($http, $location, $scope, $window, jwtHelper, AuthFactory) {
    var vm = this;
    window.VM = vm; // For debugging:

    var socket = io.connect('http://localhost:3000/#');

    vm.login = () => {
        socket.emit('sendToServer', 'JJJ');
        socket.on('test send', function(result) {
            console.log("Result received!!!", result);
        });
    };

}

我不知道该对路由器和svrUser.js进行哪些更改。 如果有人可以提供帮助,我深表感谢。谢谢

0 个答案:

没有答案