Path broke in Nodejs - javascript

I have a problem from client side with my path for a image or css, my image and css are in the same folder with index.html but index don't see it.
My folder structure:
index.html
image.jpeg
main.css
server.js
In index.html I ask the path for image and css so:
<img src="/image.jpeg">
<link rel="stylesheet" type="text/css" href="/main.css">
In server.js I ask the path for index so:
var app = require('express')();
app.get('/',function(req,res){
res.sendFile(__dirname + '/index.html');
});

Read Express docs before use it: serving static files in Express

You problem is that you have no way of serving static files.
Include this:
app.use(express.static(__dirname + '/public'));
And use the directory 'public' to store your files.
There is a question posted here that is similar to yours and which may provide further clarification. Basic webserver with node.js and express for serving html file and assets

Related

Adding CSS to EJS

Have difficulties linking my css files when using EJS.
Already looked into other answer but can't figure it out
This is the code I used reference for my css file.
EJS
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="index.css">
<title></title>
</head>
<body>
<header>
<% include header %>
</header>
</body>
</html>
The css file is in the same directory as the ejs files, the views directory. Can this cause any problems? The header is just another ejs file with some static html.
server:
const express = require("express");
const path = require('path');
const app = express();
app.set("views", path.resolve(__dirname, "views"));
app.set("view engine", "ejs");
app.use(express.static(__dirname + 'public'));
app.get('/', (req, res) => {
res.render("index");
})
app.listen(3000);
I Eventually want to move my css files in another folder but I was really wondering why this doens't work. Since the files are in the same folder I expected the relative path <link rel="stylesheet" href="index.css"> to work.
You specified that the static files (css, images, etc) are on the folder "public" :
app.use(express.static(__dirname + 'public'));
Read : http://expressjs.com/en/starter/static-files.html
Just move your css on this folder ;)
edit :
You can specify multiple static folder :
app.use("/public1", express.static(__dirname + "/public1"));
app.use("/public2", express.static(__dirname + "/public2"));
But you can add folders in your static folder :
/public1/css
/public1/lib
and use it like that in your ejs file :
<link rel="stylesheet" href="/public1/css/index.css">
The reason it doesn't work is simply because the folder containing your .ejs files is not actually being served. When rendering a view, express will locate your .ejs file locally on the server and read its contents, but it will not make it available over a HTTP connection.
You can verify this by trying to access the .ejs file directly via your browser.

Resolving dependencies in express server

I am having some trouble resolving dependencies on my express server.
Here is my project structure
Calculator
--dist
----app
-------calculator.js
-------server.js
--node_modules
--src
----app
--------calculator.js
--------server.js
----public
--------calculator.css
--------calculator.html
----.babelrc
----.gitignore
----package.json
Here is my server.js code
const express = require('express');
const app = express();
const path = require('path');
app.get('/', (req, res) => {
res.sendFile(path.resolve('./src/public/calculator.html'));
});
app.use(express.static(__dirname + '../../src/app/public'));
app.use(express.static(__dirname + './'));
app.listen(3000, () => {
console.log(__dirname);
console.log("Listening on port 3000");
});
The reason I have a dist folder and a src folder is because I am compiling my JS from ES6 from the src folder to ES5 within the app folder using Babel.
However, when I launch my node server, my html is not able to load the css file and JS file. I am using these paths to load each respectively from the calculator.html file
<link rel="stylesheet" type="text/css" href="./calculator.css">
<script type="text/javascript" src="./calculator.js"></script>
I am sure I am missing something about the way files are served on a localhost. Would appreciate the error being pointed out.
It looks like on line 9 in server.js:
app.use(express.static(__dirname + '../../src/app/public'));
you're going from the app folder up to src, up to the root, back down into src, back into app, and then trying to go down into public. However by your project structure diagram, public isn't inside app but rather beside it. You'd want something more like app.use(express.static(__dirname + '../public')); In addition, I'd recommend using the path module that's built into Node. It'll make sure you don't have mistakes in path creation.
EDIT: Sorry, that was incorrect. I didn't see that you were transpiling your server code as well. You'll want to use these lines, which should fix both:
app.use(express.static(__dirname + '../../src/public'));
app.use(express.static(__dirname));
This is assuming you run the server.js file present in dist/app and not the one in src/app.
Alright, this worked for me although I'm not a 100% sure why exactly.
I set my express static file delivery to the following
app.use(express.static(__dirname + '/../../src/public'));
app.use(express.static(__dirname));
My __dirname was shown to be Calculator/dist/app so changing the src attributes for the CSS and JS in the HTML file to this worked
<link rel="stylesheet" type="text/css" href="./calculator.css">
<script type="text/javascript" src="./calculator.js"></script>
I am assuming this works because I set my express static folder to look inside the /src/public folder and since my current directory was the /dist/app folder, I could serve the JS file directly from there?
Try one of these ...
app.use(express.static(__dirname + '/./src/app/public'));
app.use('/', express.static(__dirname} + '/./src/app/public')); // __dirname doesn't include the ending back slash, I think?
The first will always look in your static directory, and the second will look in your static directory for '/' and below. See https://expressjs.com/en/4x/api.html#app.use for more.
And then ...
Change your HTML so the src attributes will be '/calculator.css', etc

Sourcing files that are retrieved with app.get()

In Node.js, I'm routing different directories in a site and am using app.get() to redirect traffic.
Problem: When using app.get(), the index.html file that is sent to the user thinks its directory is the root directory. But I have libraries that are in the sub-directory that aren't being reached.
Example:
app.get('/htmlFileInD1', function(req, res){
res.sendFile(__dirname + '/root/D1/htmlFileInD1.html');
}
But in htmlFileInD1.html is:
<img class="wifi_battery" src="img/wifi_battery4.gif">
The image is being called from the root directory, but the img folder is in the D1 subdirectory.
I don't want to do:
<img class="wifi_battery" src="root/D1/img/wifi_battery4.gif">
since I have a lot of other libraries that I would have to change the source for.
What's the best way for the app.get() file to still call on its native directory?
You can serve your static assets like images by adding the following in your app
app.use(express.static(__dirname + '/root/D1/'));

Express JS: Can I still have <scripts> in my index.html

When converting an index.html page to be served up by Express, instead of Webstorm, I noticed that all my scripts suddenly reported 404 - Not Found, where previously they were found just fine.
Should I not be serving up a page from Express that has a bunch of tags? If it is OK to do so, how come they are all 404-Not found now, where previously they were found just fine?
EDIT: Directory structure:
project
--- src
--- js
main.js
--- css
index.html
app.js <-- all the express code
Express code includes these lines:
app.use(express.static(__dirname + '/js'));
app.use(express.static(__dirname + '/css'));
Make sure Express is set up to serve your static assets. By default it will serve these from /public
app.use(express.static(path.join(__dirname, 'public')));
You can add your scripts there (recommended!) or add additional express.static statements pointing to your specific scripts folder.

I am having issues getting the src tags for my js and css files to work

I am trying to work on a sample web application using HTML5 boostrap express js angular and jquery. I have been fighting with the source tags to the js and css files I am trying to include and just cannot get them to work unless I use one that is hosted online. If any one has some spare time here is what my header code looks like
index.html
<script type="text/javascript" src="/bower_components/jquery/dist/jquery.js"></script>
<link rel="stylesheet" type="text/css" href="/bower_components/bootstrap/dist/css/bootstrap.css"/>
<script type="text/javascript" src="/bower_components/bootstrap/dist/js/bootstrap.js"></script>
<link rel="stylesheet" type="text/css" href="style.css"/>
------------------------------------------------------------------------------------
app.js
var express = require('express');
var path = require('path');
var app = express();
//config
app.set('views', __dirname + '');
app.engine('html', require('ejs').renderFile);
//routes
app.get('/',function(req,res){
res.render('index.html')
});
//server
app.listen(1337,function(){
console.log('ready on port 1337');
})
This is a screenshot of of my file stucture
My server is running in the app.js located in the root folder. I have tried many variations of ../ and no slash and even the ~ to attempt to get this to operate. Thank you for your time in advance.
EDIT So while I have been messing around I realized if I open the index.html file without running it on my express server it works just fine. I have updated the code portion above to include my app.js.
SOLVED
A big thanks to suchit,dfsq,and Anubhav.
So since I was using express I needed to tell express how to properly path to my static src files "aka the js and css" inside of my app.js. So the answer I provide is only relevent if you are running your application on an express server. I will provide the code that was added to my app.js file and to my index.html file to come to a solution.
app.js
app.use(express.static(__dirname + '/bower_components'));
--------------------------------------------------
index.html
<script type="text/javascript" src="/bower_components/jquery/dist/jquery.js"></script>
<link rel="stylesheet" type="text/css" href="/bootstrap/dist/css/bootstrap.css"/>
<script type="text/javascript" src="/bootstrap/dist/js/bootstrap.js"></script>
<link rel="stylesheet" type="text/css" href="style.css"/>
Sincerely,
Fred K
Add app.use(express.static(__dirname + '/bower_components')); to app.js (it is a configuration) then link to the static files can be written as <script type="text/javascript" src="/bootstrap/dist/js/bootstrap.js"></script>
This assumes all your static files such as javascript and CSS files reside in your /bower_components folder.
The statement instructs the app to make /bower_components the root for all the static files.
app.js now looks like
var express = require('express');
var path = require('path');
var app = express();
//config
app.set('views', __dirname + '');
app.engine('html', require('ejs').renderFile);
app.use(express.static(__dirname + '/bower_components'));
//routes
app.get('/',function(req,res){
res.render('index.html')
});
//server
app.listen(1337,function(){
console.log('ready on port 1337');
})

Categories

Resources