Express: subfolder paths having issues - javascript

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.

Related

express js problem with showing html.index?

this is my first try with express js and I'm trying to display index.html ho is exist in ''public'' folder I don't know where is the problem
in the side server I have :
const express = require('express');
const app = express();
app.listen(3000, () => console.log('listening at 3000'));
app.use(express.static('public'));
and I reload the server with git bash ;
and I put my index.html inside ' public' directory and I rerun my server I put http://localhost:3000/
in my browser and shows "Cannot get " help please and thanks in advance
Please check first console express is running or not then trigger atleast one api like api.get('pathname' , callbak) Using route
Then raise question
you have to make route and render index.html
const express = require('express');
const app = express();
app.use(express.static('public'));
app.route('/',function () {
res.sendFile('index.html');
});
app.listen(3000, () => console.log('listening at 3000'));
You need to give the index option to express.static() like this:
app.use(express.static('public', {index: 'index.html'} ));
Keep in mind that express's static rendering doesn't make it into a full featured web server to serve files (like apache, nginx, and others).
Your code works as it is when the public directory is inside the Current Working Directory (i.e. The directory you are in when you run npm start, or node src/index.js).
If you want to make sure the directory is found wherever you start the script, use a path relative to your script using the native path module.
For example, if your folder structure is like this:
my-project/
|_ public/
| |_ index.html
|_ src/
| |_ index.js
|_ package.json
you need to go up one level (..):
const Path = require('path'); // <------- add this native module
const express = require("express");
const app = express();
app.listen(3000, () => console.log("listening at 3000"));
const publicPath = Path.join(__dirname, '../public'); // <-- get path
app.use(express.static(publicPath));
If the directory is in the same folder as your script, you can just do
Path.join(__dirname, 'public');

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

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');
});

How to setup simple static server where path '/' points to index.html within dirrectory?

There might be a very simple solution to this question, but I am not able to find answer online and due to my practice with node I can't figure it out either.
I'm trying to set up a simple server.js file that listens on port 80 and serves /dist/index.html file when users enter root address, so example.com
This is my project structure
dist/
index.html
bundle.js
node-modules/
package.json
server.js
You can create a static server with express:
server.js
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/dist'));
app.listen(8080, function() {
console.log('Listening on port: ' + 80);
});
You simply run node server.js to get the static server. This app can also be deployed.
http-server is a simple method of serving from your file system. Install that, then just run http-server -p X in the command line in your project folder, substituting your port number for X

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