如何使用express从单独的文件为客户端创建api?

时间:2016-09-20 18:57:37

标签: javascript node.js express

我是nodejs的新手,我想从app / routes.js处理所有路由和api,我有路由器,我用来获取和发布客户端。我没有看到服务器与客户端之间的任何响应,代码如下,任何想法?

app.js

var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('./app/io').initialize(server);
var ditconsumer = require('./app/consumers/ditconsumer');

ditconsumer.start(server);
server.listen(3000, function () {
    console.log('Example app listening on port 3000!');
    //stconsumer.start();
});

应用程序/ routes.js

var express  = require('express');
var router = express.Router();
var dirDirectory = require('./app/serverfiles/ditDir');

module.exports = function(app){

   router.get('/getAllFiles',function(req,res){
    dirDirectory.readDirectory(function(logFiles){
        res.json(logFiles);
        console.log(logFiles);
    });
});

    //other routes..
}

1 个答案:

答案 0 :(得分:2)

所以这就是你做错了

  1. 您不需要路由应用/路由并将其用作中间件
  2. 您必须在app / routes.js中导出路由器
  3. 这是您更改的代码,请尝试一下,我知道它是否有帮助

    var express = require('express');
    var app = express();
    var myroute=require('./app/routes.js');
    app.use(myroute);
    var server = require('http').createServer(app);
    var io = require('./app/io').initialize(server);
    var ditconsumer = require('./app/consumers/ditconsumer');
    
    ditconsumer.start(server);
    server.listen(3000, function () {
       console.log('Example app listening on port 3000!');
    //stconsumer.start();
     });
    

    应用程序/ routes.js

     var express  = require('express');
     var router = express.Router();
     var dirDirectory = require('./app/serverfiles/ditDir');
    
    
    router.get('/getAllFiles',function(req,res){
      dirDirectory.readDirectory(function(logFiles){
          res.json(logFiles);
           console.log(logFiles);
      });   
     });
     module.exports=router;  
       //other routes..
      }
    

    如果这可以解决您的问题,请告诉我