2016-09-28 61 views
0

我在express node.js中是全新的。我有一个文件夹结构,如:如何获取Express nodejs中的路径权限?

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

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

我写了express-ws这样的server.js

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.htmlindex.html链接到直接访问块。

回答

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); 
+0

我怎么没看到'app.use(path.join(__目录名,express.static('public')));'可能是正确的语法。 'express.static()'返回一个中间件函数。你为什么要将一个中间件函数传递给'path.join()'? – jfriend00

+0

谢谢@ jfriend00,我已更新代码,这是错字错误 –

+0

但是当我点击'index.html'中的链接时,我没有重定向到'home.html'。我是否应该链接该HTML也?此外,该home.html正在使用一些CSS,JS文件夹。我想我应该把home.html放在公共文件夹中。 – user2986042

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

+0

谢谢..我会检查 – user2986042