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.
Related
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')))
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')));
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);
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"]
Following is a small server (app.js) which is is simply calling index.jade file to add jquery.js, underscore.js and backbone.js for later use. But its not working.
My directory structure is:
base
app.js
public
jquery.js
underscore.js
backbone.js
theapp.js
views
index.jade
My app.js file is:
var express= require("express"),
http = require("http"),
path = require("path");
var app= express();
app.use(express.static(__dirname+ "/public"));
app.get("/", function(req, res){
res.render("views/index.jade");
});
app.listen(3000);
My index.jade file is:
#main
script(src= "jquery.js")
script(src= "underscore.js")
script(src= "backbone.js")
script(src= "theapp.js")
When I run localhost:3000 in the browser, it says: Error: Failed to lookup view "views/index.jade"
(Localhost is working fine with another node.js program)
Please help. Thanks a lot!
Dont include the .jade
res.render("views/index");
Assuming your view engine is already setup to use Jade. (app.set('view engine', 'jade');)
You also probably dont need to specify the "views" folder, check for the line
app.set('views', path.join(__dirname, 'views'));
in your app.js - this is the root directory for your views, so you'll only need:
res.render("index");