如何在Express nodejs中获取路径权限?

时间:2016-09-28 07:00:37

标签: html node.js express

我在express node.js中是全新的。我有一个文件夹结构,如:

/Express 
   --server.js
   --index.html
   --home.html
      /css/
      /js/
      /images
      /fonts

index.html我正在访问某些javascript (js folder)images (images folder)fonts (fonts folder)。我也是从home.html页面链接index.html。我还需要直接阻止访问home.html

我用server.js写了一个express-ws,如下所示:

  var express = require('express');
  var app = express();
  var expressWs = require('express-ws')(app);
  var path = require('path');

  //accessing index.html
  app.get('/', function(req, res){
    res.sendFile(path.join(__dirname+'/index.html'));

   });

   //How can i acess all the files inside the JS , CSS , Image and Font folder here ???  

    //Also How can i link home.html from Index.html File and block home.html accessing publicly  

   app.ws('/', function(ws, req) {
      ws.on('message', function(msg) {
       console.log(msg);
      });
      console.log('socket', req.testing);
    });

  app.listen(8888); 

有关如何使用index.htmlserver.js访问JS,CSS,图像和字体文件夹中的所有文件的任何建议吗?同时将home.html的{​​{1}}与直接访问阻止相关联。

2 个答案:

答案 0 :(得分:3)

您应为public或其他任何内容创建静态内容的单独文件夹,然后使用express.static()来提供静态内容。所以这里是你更新的目录结构

/Express 
   --server.js
   --index.html
   --home.html
   --/public/ (directory)
          --/css/ (directory)
          --/js/ (directory)
          --/images/ (directory)
          --/fonts/ (directory)

,您的更新代码将是

  var express = require('express');
  var app = express();
  var expressWs = require('express-ws')(app);
  var path = require('path');

  //for js, css, images and fonts
  app.use(express.static(path.join(__dirname, 'public')));

  //accessing index.html
  app.get('/', function(req, res){
    res.sendFile(path.join(__dirname, 'index.html'));

   });

   app.ws('/', function(ws, req) {
      ws.on('message', function(msg) {
       console.log(msg);
      });
      console.log('socket', req.testing);
    });

  app.listen(8888); 

答案 1 :(得分:1)

在需要路径后添加以下内容

// serve index.css at localhost:3000/index.css
app.use(express.static('css')); // looks in current directory for css folder

// serve index.js at localhost:3000/static/index.js
app.use('/static', express.static('js')); // looks in current directory for js folder and appends /static to URL

app.use(express.static('fonts'));

Reference on serving static files from express