如何让路由器在不同的文件中工作

时间:2017-07-11 02:48:05

标签: node.js express router

如何正确导出路由器模块以与showscreen = true语句一起使用?这是我试图做的简化版本。

server.js

var express = require('express');
var app = express();
var http = require('http').Server(app);
const path = require('path');
var io = require('socket.io')(http);
var showscreen = require('./listening.js');
var router = express.Router();
app.use(express.static(__dirname + '/server'));
    app.get('/', function(req, res){
    console.log("hello");
    res.sendFile('C:/Users/O77616/Documents/practiceCode/client.html');
});

router.get('/server', function(req, res){
console.log("hello");
res.sendFile('C:/Users/O77616/Documents/practiceCode/grumpy.html');
});

app.post('/', function(req,res) {
   res.send('post it all');
});

http.listen(3000, function(){
    console.log('listening on localhost:3000');
});
module.exports = function(app) {
   app.use('/server', router); 
};

listening.js

var server = require('./server.js');
var showscreen = true;
if (showscreen) {
   app.use('/server', server);

  //possibly insert more to make router.get work
}

所以我想导出router.get方法,以便在listen.js方法中使用,具体取决于showscreen是否为true。目前的app尚未定义 我按照这个教程,但我仍然困惑 https://expressjs.com/en/guide/routing.html

评论更新:

server.js

var io = require('socket.io')(http);
var express = require('express');
var routes = require('./routes/index');
var app = express();

var http = require('http').Server(app);

app.use('/', routes);

app.get('/', function(req, res){
   console.log("hello");
   res.sendFile('C:/Users/O77616/Documents/practiceCode/client.html');
});

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

路由/ index.js

 var express = require('express');
 var router = express.Router();
 var showscreen = true;

if (showscreen) {
    router.get('/', function(request, response){ 
    response.sendFile('C:/Users/O77616/Documents/practiceCode/grumpy.html');
    });
}

module.exports = router;

我删除了listen.js文件。不确定这是否清楚,但我想要它,所以如果showscreen是真的grumpy.html将出现,否则client.html,以及我更复杂的代码的工作方式(这是非常简化的)showscreen只能在index.js中访问< / p>

1 个答案:

答案 0 :(得分:1)

在您的server.js中添加以下代码

var express = require('express');
var routes = require('./routes/index');
var app = express();

app.use('/', routes);

//与初始化和启动服务器相关的其他代码

在您的路线文件夹中创建一个index.js。有以下代码

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

/* GET index page. */
router.get('/', function(request, response){
   //code to execute 
});

module.exports = router;

希望你明白。