Express.js just won't serve static files - javascript

I am trying desperately to get it working that my express server serves statics files but I just can't get it to work... I already tried multiple attempts at solving it but none of it worked.
So my folder structure is the following:
App
- Web
-- public
--- images
--- css
-- Server.js
The code from my server is the following
const express = require('express');
const app = express();
app.use('/static', express.static('./public'));
const server = app.listen(80, function() {
const host = server.address().address;
const port = server.address().port;
console.log(`Server is running on ${host}:${port}`);
});
It just won't serve the files..
No matter how I change the usage of the public folder. I already tried with path.join and __dirname but none of it worked. I only get the express error Cannot GET /static ...

This can happen when the current working directory is not what you think it is and hence ./public doesn't resolve to the right path. The safer way to do this is to use __dirname, the directory of the current file:
app.use('/static', express.static(path.join(__dirname, 'public')));

Related

Static files not showing on express server

I am currently trying to get my JS express server to display my static HTML files using this code.
My JS Express code
**When I run my server I get this error message Error: ENOENT: no such file or directory, stat: and the directory path to the file. the directory path exists so I don't understand why it wont show the file and its contents. could someone explain this to me please. **
What I have tried in addition to my written code.
**I have tried changing the location of my project entirely and that didn't work.
I have tried using app.use, __Fileneme instead of __dirname, rewriting the code nothing works.
Im using Node. js I have express installed and required I have rewritten the code several times to be sure the error was not syntax error "although VS code would have made me aware of any syntax errors" I just at a loss now. this is a simple server that should display my html files just fine yet nothing I do works.**
try adding this line at the top:
// where /public is the folder where 'welcome.html' is
app.use('/public', express.static(__dirname+'/../public'));
the npm path package may be helpful as well
app.get('/Home', (req, res) => {
console.log(path.join(__dirname ,'/public/welcome.html'));
res.sendFile(path.join(__dirname ,'/public/welcome.html'));
})
const express = require('express');
const app = express();
app.use(express.static('public',{
extensions: ['html', 'htm']
}));
// Listen to the App Engine-specified port, or 8080 otherwise
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`Server listening on port ${PORT}...`);
});

Basic Node and Express: Serve Static Assets

let express = require('express');
let app = express();
app.use(express.static('public'));
I am trying to solve freecodecamp's "Basic Node and Express: Serve Static Assets" challenge but it keep says "not working. Could someone help me? Thanks.
This is the path folder The main files in my directory
If your public folder is whithin the same directory of your main.js file, you can use:
const path = require('path');
app.use(express.static(path.join(__dirname, "public")))
As described in express documentation:
If you run the express app from another directory, it’s safer to use the absolute path of the directory that you want to serve:
const path = require('path')
app.use('/static', express.static(path.join(__dirname, 'public')))

how can I render the css files when i use express.js?

I am grouping my files like so:
node_modules
structures
{HTML Files}
styles
{CSS Files}
app.js
package-lock.json
package.json
I've already required those:
const express = require('express');
const app = express();
const path = require('path')
what do I do next?
I assume that you're somewhat of a beginner with Node/Express.
I recommend you learn more about how express works before deploying this into an actual app.
Let's get something straight: I believe that you only have a group of HTML files that you want to show to the user under the file names eg. example.com/about.html with the homepage HTML file being called index.html so that express knows what to show where.
This is the simplest way I could think i'd achieve this effect.
const express = require('express');
const app = express();
const path = require('path');
// This is the port where the application is running on
// Uses the server's enviroment variable named PORT if is defined else
// this will use port 5000
// the page can be seen locally at http://localhost:5000/
const PORT = process.env.PORT || 5000;
// This line makes the app created earlier use the middleware that express provides for "rendering" static files
// inside the express.static method we give a path to the static files
// to create that path we use the path.join method provided by the path module we imported earlier
// this method takes in all the paths that need to be joined.
// the __dirname is the directory the application was launced from (you can use process.cwd() to get the root)
// and ofcourse the structures is the folder which contains all your HTML files
app.use(express.static(path.join(__dirname, "structures")));
// Now we do the same thing we did before but we add the middleware for the styles under the "/styles" URI.
app.use("/styles", express.static(path.join(__dirname, "styles")));
// This will start the server at the PORT which we defined earlier.
app.listen(PORT);

create-react-app build service-worker.js and manifest.json not found

I have created an app with create-react-app. I have built it and I have written a simple express app for serving the react built app.
I have some problems with the static files and the files which are in the root folder of express app, (e.g. manifest.json, service-worker.js). Now I get 404 on both these files.
How can I treat this files in express? They must be in the static folder? I have to modify the react app?
I went to see the file generated by the react build, in which the file 'service-worker.js' is imported and the string starts with '/' (that is '/service-worker.js')
(I have not touch the files for the pwa since I created the project)
Here there's my root folder of my express app
I have only added the project.json and the index.js (and obviously the node_modules), the other files are those from the react build.
Here my express app:
const compression = require('compression');
const bodyParser = require('body-parser');
const express = require('express');
const app = express();
app.use('/sketches', express.static('sketches'));
app.use('/static', express.static('static'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(compression());
app.get('/', (req, res) => res.sendFile(__dirname + '/index.html'))
app.listen(process.env.PORT || 3000, () => console.log('server listening!'))
Adding this line of code I get the service-worker.js but I can't get the files in the sketches folder.
app.use('/', express.static(__dirname));
I had a same problem i resolved it by following these steps.
warning: i am new to these technologies and i don't know much about web security. this maybe not the best way of doing it.
i get it work using ejs template engine and express but it should work in your case as well.
1) create-react-app
2) yarn build
3) copy static folder into public
4) copy service-worker.js inside static folder also
5) go inside main Ctrl + f
6) type /service-worker.js in search hit Enter
7) you will see somthing like that var e="/service-worker.js";
8) change into var e="/static/service-worker.js
9) finally open service-worker.js change /index.html to /
precacheConfig=[["/","d6be891ca003070326267be1d2185407"]

Why CSS and Bootstrap elements disappear with node express server?

I firstly made a basic node server like this:
var connect = require('connect');
var serveStatic = require('serve-static');
connect().use(serveStatic(__dirname)).listen(8080, function() {
console.log('Server running on 8080...');
});
Then I replaced it with an express server like this:
var express = require("express");
var app = express();
var path = require("path");
app.get('/',function(req,res){
res.sendFile(path.join(__dirname+'/index.html'));
});
app.use(express.static("public"));
app.listen(8080);
console.log("Running at Port 8080");
With the first one, everything worked fine. CSS, JQuery, images etc..., but with the second one, some of my style elements totally disappeared and it can't reach the pictures on the site. What did I miss? How can I solve it?
You are not serving static files.
app.use(express.static("public"))
This would serve all files from /public directly on the root of your server /. If you want to serve them at /static you need to modify the code a bit.
app.use("/static", express.static("public"))
Example
File Structure
├── node_modules
├── package.json
├── public
| └ style.css
|
└── server.js
server.js
var express = require("express")
var app = express()
app.use(express.static("public"))
app.listen(3333)
After running server.js you should be able to access http://localhost:3333/style.css (and every other file in the /public directory)
In order to serve static files have a look at https://expressjs.com/en/starter/static-files.html which shows you can use:
app.use(express.static('public'))
app.use(express.static('files'))
to serve static files from the public and files folder. In your example code you are only serving the index.html.

Categories