我正在尝试将socket.io集成到我的Web应用程序中。 socket.io的文件如下所示:
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var mongoose = require('mongoose');
app.use(express.static(__dirname));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
var Message = mongoose.model('Message',{
name : String,
message : String
})
mongoose.connect('mongodb://localhost/simple');
app.get('/messages', (req, res) => {
Message.find({},(err, messages)=> {
res.send(messages);
});
});
app.post('/messages', function(req, res){
Message.create(req.body, function(err, message){
if(err){
return console.log('error', err);
}
io.emit('message', req.body);
});
});
io.on('connection', () =>{
console.log('a user is connected');
});
var server = http.listen(process.env.PORT, process.env.IP, function(){
console.log('server is running');
});
但是,我的主应用程序的app.js文件如下所示:
var express = require("express"),
app = express(),
bodyParser = require("body-parser"),
mongoose = require("mongoose");
mongoose.connect("mongodb://localhost/simpleapp");
app.get('/', function(req, res){
res.render('landing');
});
app.listen(process.env.PORT, process.env.IP, function(){
console.log("Server is Live!!");
});
我现在遇到的问题是合并这些文件,以便它们可以作为一个文件工作。具体来说,如何创建一条适用于所有代码的app.listen路由?