Resolving dependencies in express server - javascript

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

Related

Express: subfolder paths having issues

I have a project, which is meant to be both downloaded as a standalone folder (No Node/Express), that can be run directly from the file system, and to be worked on in a local environment (localhost using node/express). Right now my file system looks like this:
main folder
client
images
Image1.png
Image2.jpeg
sounds
Sound1.mp3
Sound2.wav
js
loader.js
Engine.js
...
main.mjs
index.html
app.js
node_modules
...
package.json
package-lock.json
I need the client folder to be run on its own, loaded from the file system, so going to localhost or opening the index.html file does the same thing. However, right now I need to change every link inside of the client folder for this to work.
For example, inside of loader.js, I have a line that looks something like this:
Image1 = new Image();
Image1.src = '/client/images/image1.png'
But when It is run as a stand alone file, it needs to be:
Image1 = new Image();
Image1.src = '../images/image1.png'
How do I set up my express server to handle the second condition and treat it as the first? Right now it will not send the files over, will just respond with a 404 for any file that is requested, except for the index. It looks like this:
const express = require('express');
const app = express();
const server = require('http').Server(app);
app.get('/',(req, res) => {
res.sendFile(__dirname + '/client/index.html');
})
app.use('./', express.static(__dirname + '/client'));
app.use('../', express.static(__dirname + '/client'));
const port = process.env.PORT || 2000;
server.listen(port);
I am new to express, so any advice is appreciated.
Turns out, it was an easy fix, just use:
app.use(express.static(__dirname + '/public'));
Creating virtual paths was the issue, so by omitting the first argument, everything works now.
./ refers to the current directory, ../ is one up, and /js is the js folder.

Path broke in Nodejs

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

Having all website paths load the same static website in express

In my express server, I want to have all paths load the same static website, which I tried doing with the following code:
const express = require('express');
const app = express();
app.use('*', express.static('build'));
app.listen(3000);
Unfortunately I am presented with the following console errors when I navigate to any path on localhost:
:3000/main.js/:1 Uncaught SyntaxError: Unexpected token <
When attempting to view the JS file with the error, it seems to be serving index.html in its place.
I know this is due to the wildcard, but I can't think of a way to cleanly exclude all file names and paths from the static server.
I think you're looking for something a little more like this..app.use(express.static('public')
if your tree looks like
ProjectName
| server.js
| public
| index.html
you don't need the * as a parameter since setting the express.static sets the folder open to public view. This is how you separate your server code and client code. Be careful not to expose your entire project directory as people will then have access to your server code. This is why you're client files should be kept in a public folder or a www folder (common practices)
--EDIT
//this will server css, and js files so they can be linked into the html
app.use(express.static(__dirname + '/public'));
//this will force all url's except the public files to be given the index.html file.
app.use('*', function(req, res) {
res.sendFile(__dirname + '/public/index.html');
});

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.

Webpage cannot find certain files

I am building a simple sandbox/practice style website on heroku I am trying to learn nodejs and I am learning Angular. After much hit and miss I got the server to load my home.html page, however it cannot seem to find my vendor scripts. Such as my angular, contollers, and some images/css.
The path I have setup for angular is: <script src="/vendor/angular.min.js"></script>
<script src="/controller.js"></script>
This is coming from a localhostconnection by the way, so http://localhost Here is an example of what my simple index.js in node looks like:
var express = require("express");
var app = express();
app.set("port", (process.env.PORT || 5000));
app.engine('html', require('ejs').renderFile);
app.set('views engine', 'html');
app.use(express.static(__dirname + "/public"));
app.get("/", function(request, response) {
response.render("home.html");
});
app.listen(app.get("port"), function() {
console.log("Node app is running at localhost:" + app.get("port"));
});
this is located in the root of the webfiles and it points to a views folder which includes my home.html (how I got my home page to finally load) However it still says it cannot find my vendor scripts.
These are located inside their own vendor folder that is in the root folder, and the views folder is also its own folder in the root folder the setup is like so:
-views
---home.html
-vendor
--some vendor folders(bootstrap etc)
---angularjs.js and other vendor scripts
I am sure I am missing something simple here, but I am a beginner with nodejs and still learning at this point. Thank you ahead of time for the help, and let me know if I can offer anymore information.

Categories

Resources