将socket.io添加到后端,它打破了一切

时间:2017-12-30 06:20:21

标签: node.js express socket.io

好吧,正如标题所示,我使用socket.io打破了一切。主要是因为它调用表达的方式使用express来打破其他所有内容。

这是我以前的做法:

/*jshint esversion: 6*/
const express = require('express');
const http = require('http');
const bodyParser = require('body-parser');
const path = require('path');
const expressValidator = require('express-validator');
const flash = require('connect-flash');
const session = require('express-session');
const passport = require('passport');
const fs = require('fs');
const db = require('./config/db');

// Init App
app = express();

// View Engine
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));

// Bodyparser middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: false,
}));

// Set Static path
app.use(express.static(path.join(__dirname, 'static')));

哪个有奇效!它工作,但添加socket.io像这样:

/*jshint esversion: 6*/
const app = require('express')();
const http = require('http').Server(app);
const socket = require('socket.io')(http);
const bodyParser = require('body-parser');
const path = require('path');
const expressValidator = require('express-validator');
const flash = require('connect-flash');
const session = require('express-session');
const passport = require('passport');
const fs = require('fs');
const db = require('./config/db');

// Init App
// app = express();

// View Engine
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));

// Bodyparser middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: false,
}));

// Set Static path
app.use(express.static(path.join(__dirname, 'static')));

使用express.*打破所有内容,因为它表示未定义express。所以我的静态路径被破坏,当然应用程序崩溃。我尝试了几种解决方案,但无济于事。

哎呀忘了添加错误:

  

app.use(express.static(path.join(__ dirname,'static')));           ^

     

ReferenceError:express未定义

1 个答案:

答案 0 :(得分:1)

试试这个。这个想法是你需要导入快递。一旦定义了其余部分,就可以使用Socket.io。

/*jshint esversion: 6*/
const express = require('express');
const http = require('http');
const bodyParser = require('body-parser');
const path = require('path');
const expressValidator = require('express-validator');
const flash = require('connect-flash');
const session = require('express-session');
const passport = require('passport');
const fs = require('fs');
const db = require('./config/db');

// Init App
const app = express();

// Init http server
const server = http.createServer(app);

// Init socket
const socket = require('socket.io').listen(server);

// View Engine
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));

// Bodyparser middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: false,
}));

// Set Static path
app.use(express.static(path.join(__dirname, 'static')));