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

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.

Related

How to make express serve static files from another upper directory?

If I have an nodejs express application with folowing folder structure:
-src
- client
- public
- css
- js
- ...
- views
- server
- server.js
How can I serve the static files in the public folder from the server.js file, since it is located above the index.js root location?
How should the:
app.use(express.static();
look like?
----UPDATE---
SOLVED this by using:
app.use(express.static(path.join(__dirname, '/../client/public')));
Actually solved my problem by using:
app.use(express.static(path.join(__dirname, '/../client/public')));
You can use path.join()
app.use(express.static(path.join(__dirname,'public')));
just do this, (as per your directory structure)
app.use(express.static(path.join(__dirname, 'src/client/public')));
// http://localhost:3000/hello.html
or
app.use('/static', express.static(path.join(__dirname, 'src/client/public')))
// http://localhost:3000/static/hello.html

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

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

Troubleshooting node.js error

I just inherited a node.js project, where I'm suspicious that some of the original boilerplate necessary for a node project hasn't been finished. This is also my first time using node.js.
Anyway, when I run node app.js, the correct port boots up and everything, but the app can't load a number of the script files (the error "Uncaught SyntaxError: Unexpected token <" is given on each js file unable to be loaded). I've tried to troubleshoot this error, there are a lot of resources online for it, but I haven't been able to nail it down. I tried adding type="text/javascript" to each of the script tabs but it didn't change anything.
When I click to troubleshoot the incorrect loading paths of the scripts, they all bring me to the index.html page. Thus, for some reason, it seems like this section of the code from the app.js file isn't working:
// serve all asset files from necessary directories
app.use('/js', express.static(__dirname + '/public/js'));
app.use('/css', express.static(__dirname + '/public/css'));
app.use('/partials', express.static(__dirname + '/public/partials'));
app.use('/lib', express.static(__dirname + '/public/lib'));
// JSON API
app.get('/api/name', api.name);
// redirect all others to the index (HTML5 history)
app.all('/*', function(req, res, next) {
res.sendfile('index.html', { root: __dirname + '/public' });
});
However, it looks like it should be working properly (following the paths of the files). Any ideas?
Almost certainly the app.all route is sending back HTML for a request that should be sending javascript. You need to look at the specific URLs that the browser is fetching as script tags but the server is sending back HTML. The corresponding .js files probably are just not there under public/js which causes the router to proceed to the catch-all route.
Side note you can compress your express.static routes to just this because of how your URLs line up with the filesystem structure.
// serve all asset files from necessary directories
app.use(express.static(__dirname + '/public'));

exclude a folder from expressjs routing

On my expressjs app, public assets are loaded in this way:
app.use(express.static(__dirname + '/public'));
And then I redirect all requests to the index, to handle every path with Backbone
app.get('*', routes.index);
Why the /public folder is redirect too?
Also if i try to add '/public' as a first argument, it doesn't work:
app.use('/public', express.static(__dirname + '/public'));
For anyone who get any problem related to static files serving:
Before evaluating possible solutions to the problem, be sure to define express.static before the app.use(app.router).
I found lots of examples online: sometimes its defined below, sometimes not.
Putting it first solved all my problems.
app.use(express.static(path.join(__dirname + '/public')))
app.use(app.router)
After you placed the static router before app.router, express will attempt to serve requests first by matching a file from the static folder (public), if there's no match, it will pass it to routes.index as the following rule matches everything;
app.get('*', routes.index);
Also, to match any file from public dir, you need not use /public/ in the request url.
For example to fetch public/images/icon.png or public/js/scripts.js, you will only need to access /images/icon.png or /js/scripts.js. If you invoke a /public request, it will not match anything in static dir, and pass the request on to routes.index.
Hope it helps.

Categories

Resources