Node express server not serving images folder - node.js

When I run my bundled React app on the production server, it can't find my image files and I'm not sure why. I'm fairly sure it's got something to do with my node express configuration and/or my .ejs template file.
server.js
var express = require('express')
var app = express();
const path = require('path');
app.use('/static', express.static(__dirname + '/static'));
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.get('*', function (req, res) {
res.render("index");
});
const port = process.env.PORT || 3000;
const env = process.env.NODE_ENV || 'production';
app.listen(port, err => {
if (err) {
return console.error(err);
}
console.info(`Server running on http://localhost:${port} [${env}]`);
});
index.ejs
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Production Server</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link href="https://fonts.googleapis.com/css?family=BenchNine" rel="stylesheet">
<link rel="stylesheet" href="../static/css/main.css">
</head>
<body>
<div id="root"></div>
<script src="../static/js/bundle.js"></script>
</body>
</html>
My CSS stylesheet is called in the template file, and all JS is bundled into bundle.js which is referenced in the script tag. I'm not sure how to get my application to recognise the /img folder though, as at the moment it doesn't.
Here's my file structure:
- static
- css
- main.css
- js
- bundle.js
- img (contains all image files)
When I run the app however, and I open 'Sources' in Chrome console, the /img file is not being served.
I thought this line indicates that express serves everything in the /static folder...
app.use('/static', express.static(__dirname + '/static'));
...yet only two out of three files are being served.
Would massively appreciate if anyone can tell me where I'm going wrong with my setup.
Thanks in advance.

The source tab in the DevTools will only show the contents that are being used by the browser in your case index.ejs, it's only using .js and .css files
in Index.ejs you are loading
<script src="../static/js/bundle.js"></script> and <link rel="stylesheet" href="../static/css/main.css">
so that means the middleware app.use('/static', express.static(__dirname + '/static')); will check whether or not the /js/bundle.js and /css/main.css are there in the static folder, if yes it will serve them, if not then will give file or folder not found.
That means whatever you will load from the static folder in index.ejs or use in index.ejs only that contents and files will be present in the source tab.
Try adding a image in index.ejs from static folder and then view the source tab
or remove <script src="../static/js/bundle.js"></script> and view source tab you won't see JS folder as it's not been used by index.ejs
Always reload the server

Related

Why my browser shows blank page when I run express server (React.js)?

I'm new to React. I want to deploy my react project to Heroku. To do that I implemented a simple express server. But nothing renders on my browser at localhost:3000 when I run the server with node server/server.js. Am I missing something obvious here?
My project structure:
server.js:
const path = require('path');
const express = require('express');
const app = express();
const port = process.env.PORT || 3000;
// console.log that your server is up and running
app.listen(port, () => console.log(`Listening on port ${port}`));
// create a GET route
app.get('/*', (req, res) => {
res.send(res.sendFile(path.join(__dirname, '../src/index.html')));
});
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
</body>
</html>
There is no index.html in src. With create-react-app the file index.html it would be put into build when command npm run build is executed. It generates an index.html with urls to the JS/CSS dynamically injected. One option is you you could consider putting the React application into public, then target index.html of the build folder generated by npm run build:
// create a GET route
app.get('/*', (req, res) => {
// update this path to match how you set up express to serve static and where your build is output to
res.send(res.sendFile(path.join(__dirname, 'public', 'path', 'to', 'build', 'index.html')));
});
Also you need to make sure you have static file serving set up for express:
app.use(express.static('public'))
static can also target multiple directories in case you don't want to nest your react project too deeply:
app.use(express.static('public'))
app.use(express.static('build'))
It's fairly common to have static assets in public such as images, but regardless of the structure you choose, you need to specify a path for static assets including the HTML, CSS, and JS generated by create-react-app build.

unabe to get static css files at express.js

i am trying by first express web app and I am using ejs template to render my web page and css to style my pages.
but server is unable to render css file from public folder. i put the static file path at express .js as follow
express = require('express'),
var app = express();
i tried to put static file path to express.js
// app.use(express.static('../public'));
app.use("/public",express.static(__dirname + '/public'));
// app.use(express.static('../../public')); //./
// app.use('/', express.static(__dirname + '/public'));
//app.use(express.static(__dirname + '../../public'));
and gave link to to my signup.ejs page
<link href="/public/mystyle.css" rel="stylesheet" type="text/css">
my directory structure as follow
app
|-view
|- signup.ejs
public
|-mystyle.css
express.js
When i started my server its give me 404 not found error. although my localhost is working good only problem is my web page is unable to get css file in webpage
Are you sure the port you have entered in the app.listen() is correct?
try
app.listen(port no., 'your localhost', function() {
console.log("... port %d in %s mode", app.address().port, app.settings.env);
});
Change the following two things:
Make link relative: app.use("/public",express.static(__dirname + './public'));
No need of navigating to /public again, since express.js already searches for static files in this folder: <link href="/mystyle.css" rel="stylesheet" type="text/css">
See: http://expressjs.com/en/starter/static-files.html

How to serve static files in ExpressJS when you are routing a deep directory path?

I guess the title might be confusing. I didn't know how to word it but say i have a directory as follows:
/
app.js
/static
/styles
main.css
/views
index.html
/files
1.html
2.html
If I serve 1.html and have in it, i have a css file as
<link rel="stylesheet" type="text/css" href="static/styles/main.css">
This does not load the css file. It works fine on the index page I'm assuming because it is directly inside the views folder. Because I'm trying to access something in the files folder, its not working. Could someone point me in the right direction?
Also note I have set
server.set('views', __dirname + '/views')
server.use('/static', express.static(__dirname + '/static'));
Try removing static from href attribute
<link rel="stylesheet" type="text/css" href="/styles/main.css">
And change the static files serving configuration to
server.use(express.static(path.join(__dirname, 'static')));

Loading static assets in Nodejs

What is the correct approach to loading static files. I'm trying to use Semantic UI. I have followed the basic steps here: http://semantic-ui.com/introduction/getting-started.html. I have Node installed, NPM installed, ran the gulp process and built the files. I have also required the files like this:
link(rel='stylesheet', type='text/css', href='/semantic/dist/semantic.min.css')
script(src='semantic/dist/semantic.min.js')
My project structure is this:
server.js
views/
index.jade
semantic/
dist/
semantic.min.css
semantic.min.js
I have checked in the browser and there is no console error but those files aren't listed as a resource. I have checked the server logs and there's no error.
The only thing I can think of, is that I need to set up a public directory to serve static files like:
app.use(express.static(path.join(__dirname, 'public')));
Edit
I have attempted to do this:
app.use(express.static('public'));
And have moved the files into the public directory. It loads because I can navigate to them in the browser but they aren't being applied.
Is there anyway to require them from the semantic folder? I like them to be built and required from the same space.
Edit
View:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Title
<script src="js/jquery.min.js"></script>
<link rel="stylesheet" href="css/semantic.min.css">
<script src="js/semantic.min.js"></script>
</title>
<body>
<button class="ui button"> Follow</button>
</body>
</head>
</html>
Serverjs:
var express = require('express'),
ejs = require('ejs'),
path = require('path'),
app = express();
app.use(express.static(path.join(__dirname, 'public')));
app.set('view engine', 'ejs');
app.set('views', './views');
app.get('/', function(req, res) {
res.render('index');
});
var server = app.listen(8080, function() {
var host = server.address().address;
var port = server.address().port;
console.log('Node is listening at http://' + host + ':' + port);
});
Add this line in your app.js file.
app.use(express.static(path.join(__dirname,'public')));
Then create a folder named public in the project root directory and move the css and js files to this folder. A better way of organising things would be to
create folders named css and javascript inside the public directory and then place css and js files in these folders.
Then in your template file, include these by adding :
link(rel='stylesheet', type='text/css', href='css/semantic.min.css')
script(src='javascript/semantic.min.js')

Not able to loading static files with express

Tried all possible combinations I can think of but not able to load static files using express server.
Dir Structure
app
--todoApp.html
----server.js //node file
----jquery.js
----backbone.js
Node server
var http = require('http'),
express = require('express');
var app = express();
app.listen(3000);
app.set('views', __dirname);
app.use(express.static(__dirname));
app.engine('html', require('ejs').renderFile);
console.log(__dirname);
app.get('/', function(req, res){
//res.send('Whats up?');
res.render('../todoApp.html');
});
__dirname prints as app/js ehich is correct. But page loads with error the server responded with a status of 404 (Not Found) http://localhost:3000/js/jquery.js.
HTML loads the script like this:
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/underscore-min.js"></script>
<script type="text/javascript" src="js/backbone.js"></script>
I tried multiple things but it does not work.
Tried following:
app.use('/js',express.static(__dirname));
or
app.use('/',express.static(__dirname));
Please help.
Since the current directory is already the js directory, you don't need to specify it in the <script> tags when loading your JavaScript files:
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="underscore-min.js"></script>
<script type="text/javascript" src="backbone.js"></script>
When you set a static directory in express, that directory effectively becomes the root, so all of your static file paths should be relative to that directory.
Also, it is probably not a good idea to have your server-side code in a static directory, since this would allow anyone using your server access to your server side code. It would be better to put all of your static files in a different directory, and set that as the static directory in express.

Resources