`express.static()` keeps routing my files from the route - node.js

While working on an express project, I am trying to use an express.Router object to handle my application routes. In my main app file, I have added a static route for all my static files(css, javascript, html).
app.js
var express = require('express');
var io = require('socket.io')(app);
var bodyParser = require('body-parser');
var router = require('./include/router');
var app = express();
app.use('/', router);
app.use(express.static(__dirname + '/public'));
app.use(bodyParser.json());
io.on('connection', function(socket) {
});
app.listen(3000);
router.js
var express = require('express');
var path = require('path');
var router = express.Router();
router.get('/', function(req, res) {
res.sendFile('/html/index.html');
});
module.exports = router;
When I try to access localhost:3000 I get a 404 showing Error: ENOENT, stat 'C:\html\index.html'
Furthermore, when I try to access the static route directly(http://localhost:300/html/index.html I believe), but that gives me Cannot GET /html/index.html.
This is the tree of my public folder
public
├───css
├───hmtl
| └───index.html
├───img
└───js
Am I routing this wrong? How can I fix it?

You must inverse the order of your router
app.use('/', router);
app.use(express.static(__dirname + '/public'));
means your router will be called first and, if no middleware handles the request, then express will call static files so, if you put the static middleware first, the express will handle static files first.
It is also recommended to put static middleware first.
For your problem you should try this:
app.use(express.static(__dirname + '/public/html'));
app.use(express.static(__dirname + '/public'));
app.use('/', router);
Express will try static files first on public/html folder, then on the rest (including the public/html), i prefer putting html files on the root of public folder or maybe on a different folder (e.g public-html, static-html)

Related

why are my static files failing to load response

i am trying to get data from a html form using express
but when i try to load my static files with app.use(express.static(__dirname+"public");
in the devtools it is showing that it failed to load my response data
can anyone tell me why this is happening and a solution for this
here is the code in the first image
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.urlencoded({extended:true}));
app.use(express.static(__dirname+'public'));
app.get("/",function(req,res){
res.sendFile(__dirname + "/public/bmiCalculator.html");
});
app.post("/",function(req,res){
console.log(req.body);
res.send("hello");
});
app.listen(300,function(){
console.log("Server Hosted OK");
});
The path provided to the static middleware is incorrect. The following code __dirname+'public' will give you Calculatorpublic, i.e. / is missing. What you can do is to add the / before public:
app.use(express.static(__dirname, "/public"));
Another variation:
const path = require('path');
app.use(express.static(path.join(__dirname, "public")));

Setting up MEAN stack not rendering app-root

I'm trying to setup a basic mean stack by following this guide, but the client doesn't seem to render the app instead the body contains,
<body>
<app-root></app-root>
</body>
The file structure is exactly the same as a blank angular cli project except the addition of two extra files.
PLUS: npm install --save ejs cors express body-parser
routes/index.js
var express = require('express');
var router = express.Router();
router.get('/', function(req, res, next) {
res.render('index.html');
});
module.exports = router;
server.js
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var cors = require('cors')
var index = require('./routes/index');
// app
var app = express();
// cors
app.use(cors());
// views
app.set('views', path.join(__dirname, 'src'));
// engine
app.set('view enginer', 'ejs');
app.engine('html', require('ejs').renderFile);
// angular dist
app.use(express.static(__dirname + '/dist'));
// body bodyParser
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
// route
app.use('/', index);
// Initialize the app.
var server = app.listen(process.env.PORT || 3000, function () {
var port = server.address().port;
console.log("App now running on port", port);
});
I run an ng build and node server.js but get a blank white page in the browser.
Perhaps there is a breaking change that I'm not aware of since that guide was using angular2 (I'm using angular 6).
Since your index.html isn't directly inside the dist folder (rather, it is inside a sub-folder for some reason), try changing app.use(express.static(__dirname + '/dist')); to app.use(express.static(__dirname + '/dist/<your project name here>'));

Express server deployed, not work in openshiftapps but works fine in local

I just deployed my express.js server on openshiftapps and for some reason, one of the routes not working and I get :
Internal Server Error
Same route is fine in local.this route is my root route which only should render my index.ejs file. the other routes working just fine. I share the codes here, I hope you guys can help to see where did I do wrong.
So this is my server.js code :
var express= require('express');
var path = require('path');
var bodyParser = require('body-parser');
var index = require('./routes/index');
var accountname = require('./routes/accountname');
var app = express();
//View Engine (We Use ejs)
app.set('views', path.join(__dirname,'views'));
app.set('view engine', 'ejs');
// app.use(express.static(path.join(__dirname,'edaccounting')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use('/', index);
app.use('/api/v1/', accountname);
app.listen(8080, function(){
console.log('Server is Started on port 8080');
})
And this is my index.js :
var express= require('express');
var router = express.Router();
router.get('/',function(req,res,next){
res.render('INDEX');
})
module.exports = router;
so for this route : app.use('/', index); I get Internal server error on the real server but it's working in my local and render the .ejs file. Other route is fine in real server. I used openshiftapps and I build my node.js app there with no errors!

Express Server with Angular2 -- App stuck on "Loading..."

I have done the standard MEAN stack JS application from scratch using Angular-CLI and node/npm. I did ng init and filled out some front end stuff which works fine when I use ng serve, then I created the back end using the code posted below and typing node server in shell. It loads my index.html page which is in src/index and then I try to do a join on src which contains src/app which has my Angular2 code but I get the dreaded Loading... from within my element. I have watched multiple tutorials and they all did exactly this or similar cookie cutter server code, I cannot figure it out.
server.js:
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var index = require('./routes/index');
var event = require('./routes/events');
var port = 3000;
var app = express();
app.set('views',path.join (__dirname, 'src'));
app.set('view engine', 'ejs');
app.engine('html', require('ejs').renderFile);
app.use(express.static(path.join(__dirname, 'src')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use('/', index);
app.use('/', event);
app.listen(port, function() {
console.log("server listening on port" + port);
});
index.js:
var express = require('express');
var router = express.Router();
router.get('/', function(req, res, next) {
// res.render('../src/index.html');
res.render('index.html');
});
module.exports = router;
in Angular CLI app, run ng build or ng build --prod then node/express serve static directory dist not src.

Node.js sending html file doesn't load linked files (css, js)

I am trying to make az ExtJS application with a Node.js server. My server code currently looks like this:
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.sendfile(filedir + '/index.html');
});
app.get('/employees', function(req, res){
console.log("hello");
});
app.listen(3000);
When I open localhost:3000 in a browser, the html file is load, but not correctly. Checking in firebug I see that itt cannot find the linked files in html. For example
"NetworkError: 404 Not Found - http://localhost:3000/ext-4/ext-debug.js".
This is quite logical, since the file doesn't exist on that URL. My question would be how to fix this issue, so it could find every single linked file on my filesystem.
I'm clearly doing something wrong or missing something, I am totally new in node.
Doesn't look like you're configuring Express' static file handler.
Try adding this code:
app.configure(function() {
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.bodyParser());
app.use(express.logger("short"));
});
It would go right after var app = ... like this:
var express = require('express');
var app = express();
app.configure(function() {
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.bodyParser());
app.use(express.logger("short"));
});
app.get('/', function (req, res) {
res.sendfile(filedir + '/index.html');
});
app.get('/employees', function(req, res){
console.log("hello");
});
app.listen(3000);
And then place your static files under the ./public directory.
You'll want to use some static middleware such as: http://www.senchalabs.org/connect/static.html
note express inherits connect so you can
app.use(express.static(filedir));
Or the full thing:
var express = require('express');
var app = express();
app.use(express.static(filedir));
app.get('/employees', function(req, res){
console.log("hello");
res.send("hello");
});
app.listen(3000);

Resources