I am completely new in express node.js . I have a folder structure like :
/Express
--server.js
--index.html
--home.html
/css/
/js/
/images
/fonts
In index.html
i am accessing some javascript (js folder)
, images (images folder)
, fonts (fonts folder)
. Also i am linking home.html
from index.html
page . I need to block accessing home.html
directly also .
I wrote a server.js
with express-ws
like this :
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);
Any suggestions how can i access all the files inside the JS , CSS , Image and Font folder from index.html
with server.js
? Also linking home.html
from index.html
with direct access block .
You should create a separate folder for static content like public
or anything else and then use express.static()
to serve static content. So here would be your updated directory structure
/Express
--server.js
--index.html
--home.html
--/public/ (directory)
--/css/ (directory)
--/js/ (directory)
--/images/ (directory)
--/fonts/ (directory)
and your updated code would be
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);
add following after requiring path
// 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'));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.