Css files would not transfer using nodeJS express - javascript

I am trying to send the files of a whole project with nodeJS express, but only the html files seem to get transferred. Here is the code:
const express = require('express');
const app = express();
const port = process.env.PORT || 8080;
app.use(express.static("public"));
app.get('/', function(req, res) {
res.sendFile(__dirname + "/public/home.html");
});
app.listen(port);
console.log('Server started at http://localhost:' + port);
This is the nodeJS file, which is inside the Folder of the project. Everything else (html files, css files, js files) is inside the folder 'public' which is a subfolder inside the folder of the project.

Related

Express.js just won't serve static files

I am trying desperately to get it working that my express server serves statics files but I just can't get it to work... I already tried multiple attempts at solving it but none of it worked.
So my folder structure is the following:
App
- Web
-- public
--- images
--- css
-- Server.js
The code from my server is the following
const express = require('express');
const app = express();
app.use('/static', express.static('./public'));
const server = app.listen(80, function() {
const host = server.address().address;
const port = server.address().port;
console.log(`Server is running on ${host}:${port}`);
});
It just won't serve the files..
No matter how I change the usage of the public folder. I already tried with path.join and __dirname but none of it worked. I only get the express error Cannot GET /static ...
This can happen when the current working directory is not what you think it is and hence ./public doesn't resolve to the right path. The safer way to do this is to use __dirname, the directory of the current file:
app.use('/static', express.static(path.join(__dirname, 'public')));

How to include JS, CSS and other server-side utils to a HTML page in NodeJs using expressJs?

I could not find any solutions that worked for me.
I am trying to create a simple microservices architecture with Node.js instances. I do not use Dockerfile. The homepage microservices displays correctly the html with CSS, JS. The gateway microservice does not load the CSS, JS (the page looks broken).
homepage html here
gateway response html here
At the moment I have 2 microservices:
Express server that sends index.html as file. It loads correctly the page with assets (css, images, javascript). I have used app.use(express.static('public')).
homepage:
const express = require('express')
const app = express()
var path = require("path")
app.use(express.static('public'))
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname+'/public/index.html'));
})
app.listen(3001, () => console.log('Homepage listening on port 3001!'))
Express server that receives requests and wants to deliver content to user. I am trying to create an API Gateway to filter traffic (on authentication for example) and write logs.
gateway:
const express = require('express')
const request = require('request-promise-native')
const app = express()
app.get('/', async (req, res) => {
// Write logs in database
const uri = "http://localhost:3001/"
const result = await request(uri)
res.send(result)
})
app.listen(3000, () => console.log('Public API Gateway listening on port 3000!'))
Project structure with the 2 server files here
Any solution is really appreciated.
Thanks!
When you request the homepage from the homepage microservice and serve its html to the gateway microservice, all resources (i.e. styles, scripts and images) aren't loaded correctly. That's because in your index.html relative paths to resources are used, for e.g.
<link href="assets/styles.css"/>
so:
In homepage microservice, assets/styles.css gets resolved to
//localhost:3001/assets/styles.css, then express server serves
assets/styles.css from public directory since express is configured to serve
static files from the public directory:
app.use(express.static('public'))
In gateway microservice, assets/styles.css gets resolved to
//localhost:3000/assets/styles.css, then express server tries to serve
assets/styles.css but returns an error because the express server in the gateway
microservice isn't configured to serve static assets from any directory.
A simple solution to this problem is to redirect all the calls to the /assets in the gateway microservice to //localhost:3001/assets, so server.js in your gateway will look like this
const express = require('express');
const request = require('request-promise-native');
const app = express();
// redirect /assets to localhost:3001/assets
app.get('/assets/**', (req, res) => {
const uri = 'http://localhost:3001' + req.path;
res.redirect(uri);
});
app.get('/', async (req, res) => {
// Write logs in database
const uri = "http://localhost:3001/";
const result = await request(uri);
res.send(result);
});
app.listen(3000, () => console.log('Public API Gateway listening on port 3000!'));
You need to make your JavaScript, CSS and images be available for public use as all our files are hidden from client-side.
So What to do? Just keep all your client-side JavaScript, CSS and image in public folder and make that public folder available for client-side like:
//Using expressJs
//All your HTML will be in this folder.
app.set('views', __dirname + '/views');
//This is your HTML template to know more [what is ejs][1] and what's different between html and ejs or jade please do little research.
app.set('view engine', 'ejs');
//This is what makes your image, JS and CSS available to HTML page.
app.use(express.static(path.join(__dirname, 'public')));
How to import files from public folder?
Use following ways:
// location of all these files is in public folder like:
// public/min/css/bootstrap.min.css
// public/min/js/app.min.js
// public/images/image1.jpg
<link rel="stylesheet" type="text/css" href="/min/css/bootstrap.min.css" />
<script type="text/javascript" src="/min/js/app.min.js"></script>

transferring node app to server

I have a node server file, app.js which uses express.
The file looks like this
var express = require('express')
var app = express();
app.use(express.static(__dirname + '/public'))
app.get('/', function (req, res) {
res.send('Hello World!')
})
app.listen(3000, function () {
console.log('Example app listening on port 3000!')
});
If I run $ node app.js from my terminal it launches and if I navigate to localhost:3000 on my machine I see Hello World!.
I have uploaded the file to a server and try and navigate to the index.html file , which is in the public folder, however it doesn't work.
Maybe I am missing many steps, but can anyone advise how I can launch the node app on my server?
Your server doesn't send index.html anywhere. It only serves "/" path by sending text "Hello World!".
With Node.js, you have to tell which content you want to send for each route.
You can simply send the specific file : (sure, but dirty)
app.get('/index.html', function (req, res) {
res.send(PATH_TO_FILE/index.html);
});
Or specify which path to use to serve files by default :
app.use(express.static(__dirname + '/public'));
And you put all your public files to serve automatically in the public folder :
YOUR_PROJECT/public/AUTOMATICALLY_SERVED_FILES
Where AUTOMATICALLY_SERVED_FILES can be index.html or css/style.css for exemple.
NB : NGINX is not useful at this point.
On the server, nodejs is configured right?
I use forever with nodejs, it is useful if you would like to use nodejs like a service on linux base system.

How to point heroku hosting to angular app and index.html in subdirectory?

I'm new to deploying with heroku. Inside of my heroku repo, I have an nodejs + angular app where my app.js and all angular files are inside of a subdirectory called app/
I use grunt, and I can run my site locally without problem, and I go to localhost:8000/app. When I push to heroku, it goes through my package.json and runs the appropriate scripts to build the project. I have also already done
heroku ps:scale web=1
However, when I try
heroku open
The page says:
Application Error An error occurred in the application and your page
could not be served. Please try again in a few moments.
I believe this is because heroku isn't pointed to app/index.html, so there is no page to render. Is there any fix for this?
What does your web server configuration file (app.js/webserver.js or whatever you've named it) look like?
Here's a sample one using Express:
var express = require('express');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var app = express();
var port = process.env.PORT || 8000;
var path = require('path');
var rootPath = path.normalize(__dirname + '/');
app.use(express.static(rootPath + '/app'));
app.listen(port, function (err) {
console.log('running server on port ' + port);
});
Heroku should have no trouble finding your index.html within your app folder if the above is configured properly.

Getting express.js to show a public folder

I've recently built a quick one page app using express.js, and this is really my first js framework (actually, my first js project, so I'm really new to this). I've got a subscription to the new typography.com cloud fonts, and I'm having trouble locating the "fonts" folder that I place in the public folder. Is there a way I need to add the folder and specify a route?
Here's my app.js file:
/**
* Module dependencies.
*/
var express = require('express'),
routes = require('./routes'),
user = require('./routes/user'),
http = require('http'),
path = require('path');
var app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static('public'));
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.get('/', routes.index);
app.get('/users', user.list);
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
I haven't made any changes to the routes at all, so they are just default.
Please use express.static setting:
app.use(express.static(process.cwd() + '/public'));
And place your fonts folder in that public folder.
If you are using Heroku, you may want to look at this thread: Deploy Nodejs on Heroku fails serving static files located in subfolders
The guy explain that he struggled with "__dirname" until he specified the last version of NPM in his package.json:
"engines": {
"node": "0.10.11",
"npm": "1.2.25"
}
If that doesn't work, you might try:
// At the top of your web.js
process.env.PWD = process.cwd()
// Then
app.use(express.static(process.env.PWD + '/public'));
Instead of "__dirname"
Though, all that is probably useless if you already struggle localy.

Categories