Express/Ngnix serving the wrong html file regardless of route - javascript

Whatever file I try to serve, express always returns admin.html
If I remove admin.html, express throws an error on the admin route (caught by my removed error handler), but continues to serve the admin page on other routes, even when the page isn't there
I've the following file structure:
// /var/www/my-site:
express-app
|--public
| |--admin.html
| |--index.html
| |--index.bundle.[hash].js
| |--admin.bundle.[hash].js
| |--// more assets
|
|--app.js
|--package.json
|--package-lock.json
|--node_modules
Here are my express routes:
const port = 3000;
app.use(express.static('public'));
app.get('/admin', (req, res, next) => {
console.log('path:', path.join(__dirname, 'public', 'admin.html'));
res.sendFile(path.join(__dirname, 'public', 'admin.html'));
});
app.get('/index', (req, res, next) => {
console.log('path:', path.join(__dirname, 'public', 'index.html'));
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
app.get('/', (req, res, next) => {
console.log('path:', path.join(__dirname, 'public', 'index.html'));
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
app.listen(port, () => console.log(`Listening on port ${port}`));
I've tried using app.use(express.static('./public'));, res.sendFile(path.join(__dirname, './public/index.html')), with and without the relative path.
Here's how the path is being resolved/logged:
/: No output
/index: path: /var/www/my-site/express-app/public/index.html
/admin: path: /var/www/my-site/express-app/public/admin.html
When I use live-server locally to view index.html it opens the correct page.
When I view index.html on my server it references index.js, so I've not accidently confused the two files afaik, and I don't think it's an issue with my webpack config.
I've switched from pm2 to just using node and I've restarted the server in case it's a cache issue.
I mean Nginx is obviously directing traffic to express, but here's my config on the off chance:
/etc/nginx/sites-available/default:
index index.html index.htm index.nginx-debian.html;
server_name my-site www.my-site.io;
location / {
proxy_pass http://127.0.0.1:3000/;
}
7 hours later and I'm completely at a loss, so would appreciate any help!

Related

Serving static frontend JS file with Express JS

Hi I am having trouble Loading the frontend JS file in Express server. My file structure is like this
My Server Code -
app.set("view engine", "ejs");
app.set("views", path.join(__dirname, "views"));
app.use('/static', express.static(path.join(__dirname, 'public')))
app.get("/", (req, res) => {
// check if user is logged in, by checking cookie
let username = req.cookies.username;
if(username){
return res.sendFile(path.join(__dirname, "public/index.html"))
}else{
res.redirect("/login");
}
});
I can successfully Load the html file
But the script file index.js is not loading and i am not able to function
<script src="index.js"></script>
Can you tell me what is it i am doing wrong
The "public" folder on the back end usually refers to a folder on the server mapped to the root path of the URL. Hence try replacing the /static path with just / in express routing, and put checks for logged in status (and any other HTTP GET request processing for server root paths that does not involve serving static files) before setting up the static server itself:
app.set("view engine", "ejs");
app.set("views", path.join(__dirname, "views"));
app.use('/static', express.static(path.join(__dirname, 'public')))
app.get("/", (req, res) => {
// check if user is logged in, by checking cookie
let username = req.cookies.username;
if(username){
return res.sendFile(path.join(__dirname, "public/index.html"))
}else{
res.redirect("/login");
}
// set up static server on root path:
app.use('/', express.static(path.join(__dirname, 'public')))
});

Express in NodeJS: URL param breaks routing

I'm trying to use express to serve my index.html, its dependancies as well as handle url params. For some reason, adding a URL param seems to break the pathing.
My basic nodeJS webapp has the following folder structure:
|- server.js (nodeJS server code)
|- public (dir)
| - app.js (app logic dependancy)
| - index.html (base HTML file to be served from server.js)
index.html is importing app.js as follows:
<script type="text/javascript" src="app.js"></script>
My express routes are as follows:
app.use(express.static(__dirname + '/public'));
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
app.get('/:country', (req, res) => {
res.sendFile(__dirname + '/index.html', {country:req.params.country});
}
I want the app to be served even when the country param is used.
However, when I add the URL param route, the above route stops working because express looks for index.html in the folder root, resulting in a 404.
Eg: http://localhost:3000/usa
Error: ENOENT: no such file or directory, stat '/Users/john/Projects/TestApp/index.html'
However, when I add the URL param route, the above route stops working because express looks for index.html in the folder root, resulting in a 404. Eg: http://localhost:3000/usa
Error: ENOENT: no such file or directory, stat '/Users/john/Projects/TestApp/index.html'
You should add public to the directory path, then.
app.get('/', (req, res) => {
res.sendFile(__dirname + '/public/index.html');
});
Or, to work cross-platform:
const path = require("path")
app.get("/", (req, res) => {
res.sendFile(path.join(__dirname, "public", "index.html"))
})

Express static files not working properly

I'm doing a simple node project to practice but i can't manage to serve html file with its css styles.
I believe that it worked fine for me before with the same code but now I don't understand why it doesn't run.
I searched about it and copied some code replacing the directory's name but it doesn't change anything.
Here is my code.
I also tried with path module to join the file name and the directory name.
app.use(express.static('public'));
app.get('/', (req, res)=>{
res.send("Welcome to our website");
});
app.get("/signup", (req, res)=>{
res.sendFile(__dirname + "/index.html");
});
//My directory:
testapp1
--node_modules
--public
--styles.css
--index.html
--app.js
--package.json
--package-lock.json
In the network tab of the developer console, it says that:
status: canceled
type: stylesheet
initiator: index.html
Size: 0B
time: 29ms
waterfall: "nothing"
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', function (req, res, next) {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
Try that instead.

Different Path for Serving Static HTML files in Express

Just a quick question. Say I have 2 different static HTML files that I want to serve in Express, index.html and contact.html. I've been fiddling around and I currently use this barebone Express code to serve them:
const express = require('express');
const path = require('path');
const app = express();
app.use(express.static('public'))
app.get('/', function (req, res) {
res.sendFile('/index.html');
});
app.get('/contact', function (req, res) {
res.sendFile(__dirname + '/public/contact.html');
});
app.listen(3000, function () {
console.log('runnning on port 3000')
});
Question is, I tried to serve contact.html using
app.get('/contact', function (req, res) {
res.sendFile(__dirname + '/contact.html');
});
but it always resort to the root directory instead of the public directory. OTOH, I can server index.html just fine without having to explicitly adding /public in the response.
Can anybody point me what's the cause for that?
Thanks.
For the given file structure:
yourapp
|-- contact.html
|-- index.html
`-- server.js
The following code would work just fine:
app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html');
});
app.get('/contact', function (req, res) {
res.sendFile(__dirname + '/contact.html');
});
Assuming both index.html and contact.html have read access.
Remember, sendFile requires an absolute path and __dirname refers to your app directory. Make sure you give references according to your file location.

How can I go about serving single page html using node.js on port 80?

My project structure looks like this:
project
assets/images/
css/application.css
js/application.js
font
node_modules
index.html
server.js
package.json
My goal is to be able to run 'node server.js" in the project folder and have it serve on port 80. Going to localhost:80 or w.e would render the index.html along with its css/assets/js.
I've tried with connect, express and http but no luck...new to node.
Thanks!
First of all, change your structure:
project
assets/images/
assets/css/application.css
assets/js/application.js
assets/font
node_modules
views/index.html
server.js
package.json
First require some packages:
var express = require('express'),
app = express(),
path = require('path');
Them run in the terminal window:
npm install express
Them set up the configurations:
app.set('views', path.join(__dirname, 'views')); // This is to serve static files like html in the views folder
app.set('view engine', html); // your engine, you can use html, jade, ejs, vash, etc
app.set('port', process.env.PORT || 80); // set up the port to be production or 80.
app.set('env', process.env.NODE_ENV || 'development');
app.use(express.static(path.join(__dirname, 'assets'))); // // This is to serve static files like .css and .js, images, fonts in the assets folder
Them create your routes:
app.get('/', function(req, res) {
res.send('Hello word');
});
app.get('/something', function(req, res) {
res.send('Hei, this is something!!!');
});
If you want render the index, inside the views folder:
app.get('/index', function(req, res) {
res.render('index');
});
And finally:
app.listen(app.get('port'), function(req, res) {
console.log('Server listening at ' + app.get('port')');
});
Them access localhost:80/index
Put your assets and subdirs under ./public, then from top dir, add app.js:
var express = require('express');
var app = new express();
app.use(express.static(__dirname + '/public'));
app.listen(80, function () {
console.log('Server running...');
});

Categories