Cannot Include Js Files In Expressjs Served Index File
I'm building a web application at the moment, which has multiple pages incorporated. Each of these pages, however, have multiple views. The original design was to set each of the p
Solution 1:
As mentioned in ExpressJs documentation , you have to use express.static(root, [options])
to create a middleware that manage you website. This is the only built-in middleware function in Express.
Express app example:
Before all you have to init you express app:
var express = require('express');
var app = express();
Then you start adding your middleware:
Note: You can add multiple middlewares, and chain them sequentially. In other words, you can add headers handler before your website middleware.
Headers middleware handler example:
app.use(function (req, res, next) {
/* you can also handle https redirection */// if (req.protocol != "https") {// res.writeHead(301, {"Location": "https://" + req.headers['host'] + req.url});// res.end();// return;// }// here you can config you response headers
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
next(); // this will pass the request to the next middleware
});
Website router example:
To create middleware website with ExpressJs, you have to use express.static
with your relative website folder, and name you default page index.html
app.use("/", express.static('PATH_TO_WEBSITE FOLDER'));
Full ExpressJs app example:
var express = require('express');
var app = express();
app.use(function (req, res, next) {
/* you can also handle https redirection */// if (req.protocol != "https") {// res.writeHead(301, {"Location": "https://" + req.headers['host'] + req.url});// res.end();// return;// }// here you can config you response headers
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
next(); // this will pass the request to the next middleware
});
app.use("/", express.static('PATH_TO_WEBSITE FOLDER'));
var httpServer = http.createServer(app);
httpServer.listen(80, "HERE_PUT_YOUR_DOMAIN", function () {
console.log('HTTP: express-example running on port ' + 80 + '.');
});
Solution 2:
Your directory will be treated as static. You don't need to make a separate directory or define a separate route.
router.use(express.static( __dirname + "/../client/pages/home/"));
Post a Comment for "Cannot Include Js Files In Expressjs Served Index File"