So i have a problem with my static files. Here's my code:
const express = require ('express')
const app = express()
app.listen(4040,() => console.log("on"))
app.use(express.static(__dirname + "/public"))
Everything works. Until I change html file name in public folder
It works if it's index.html but doesn't if it's about.html or everything else.
My folders are like that:
📂Main
📂node_modules
📂public
📂assets
style.css
index.html/about.html
main.js
package-lock.json
package.json
Route must be specific, "/" for "index.html" & "/about" for "about.html". If you change from index.html to home.html, make sure your main.js (server) also follows.
const express = require("express");
const path = require("path");
const app = express();
app.get("/", (req, res) => {
res.sendFile(path.join(__dirname, "public/index.html"));
});
app.get("/about", (req, res) => {
res.sendFile(path.join(__dirname, "public/about.html"));
});
app.listen(4040, () => console.log("on"));
index.html (http://localhost:4040/)
<h1>HOME PAGE</h1>
about.html (http://localhost:4040/about)
<h1>ABOUT PAGE</h1>
Hey I believe I might know what's going on but wanted to clarify, you are wanting to serve multiple static files one "index.html" and another "about.html" and it's only working for the one called index.html? If this is the case this is because it defaults to reading the index.html file if it is present, the solution to this may be to rename your index.html to something else such as main.html, and see if that works properly.
Related
So I have server.js file that imports a router
const path = require("path");
const express = require("express");
const app = express();
const PORT = 8080;
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(require('./app/routing/htmlRoutes'));
The router looks like this
const path = require("path");
var express = require('express');
var router = express.Router();
router.get('/', function(req, res) {
res.sendFile('home.html', { root: path.join(__dirname, '../public') });
});
router.get('/survey', function(req, res) {
res.sendFile('survey.html', { root: path.join(__dirname, '../public') });
});
module.exports = router;
It does work! It renders html pages, however those html pages have css stylesheets hooked up to them and located in the same directory, but they render as blank html sheets (unstyled)...
How do I make them render with css stylesheets taken into account?
When the browser encounters the style reference of the loaded html file, it tries to load the file specified in the src attribute. Now your server script doesn't have a route for that. It will load the css if you add a route for that specific css file. However as Irshad said, the standard way to do this is to add a route for all the static files.
app.use(express.static("public"))
Right now, you are only sending home.html everytim the root is requested.
Change your code to read the requested file from the req and serve that file whatever it may be.
Why not set the middleware to serve static files (css, html) from public folder app.use(express.static("public"))
See the working example
I am serving my front end code using node.js and express.js.
Here I'm facing an issue with my file path I provided in script src on different page URLs.
my project file structure is as follows:
react_jsx/
dst/
index.html
styles.css
main-62a2a28f9255e698905d.js // creating this file using a bundler.
Both styles.css and main-62a2a28f9255e698905d.js are adding to index.html dynamically using webpack bundler. But adding correctly as
<link href="style.css" rel="stylesheet"></head> and <script type="text/javascript" src="main-62a2a28f9255e698905d.js"></script>
Node server code is as follows:
const express = require('express');
const path = require('path');
const app = express();
app.use(express.static(path.resolve(__dirname, 'react_jsx/dst')));
app.use(express.static(path.resolve(__dirname)));
// app.use('/react_jsx/dst',express.static(path.join(__dirname, '')));
app.use(express.static(path.join(__dirname, ' ')));
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, 'react_jsx/dst/index.html'));
});
const PORT = process.env.PORT || 9000;
app.listen(PORT, () => {
console.log(`App listening on port ${PORT}!`);
});
The page is working fine on the base URL. ie., on localhost:9000.
But when I'm changing the page URL, the path to the files also changes. Suppose if the page Url is localhost:9000/app/login the path to my styles.css and main-[hash].js also changes.
The file path becoming localhost:9000/app/login/styles.css and localhost:9000/app/login/main-[hash].js
How can I resolve it? I went through a lot of SO answers and resolved issue with some other file paths, but couldn't resolve issue with files that located in the same folder of index.html
I think,you can use routing.
Like :
var router = express.Router();
app.use('/app/login', router);
Give relative path from domain root in the html as shown below.
<link href="/style.css" rel="stylesheet"></head>
<script type="text/javascript" src="/main-62a2a28f9255e698905d.js"></script>
Add this to the webpack config
output: {
publicPath: "/"
}
I am trying to get the static files (images, js, css) which are all inside the public folder to be available to all my routes. I am able to ONLY load them to the index.html. The management.html files does not have access to the static files, I am getting 404 error on the Chrome console.
Folder Structure:
-app/
---index.html
---management.html
---public/
------css/
------js/
------img/
server.js:
const express = require('express');
const path = require('path');
var app = express();
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', function(req, res) {
res.sendFile('index.html', {root: __dirname })
});
app.get('/management', function(req, res) {
res.sendFile('management.html', {root: __dirname })
});
app.listen(3000);
Inside your HTML files you are probably referring to the relative paths of the static files. For example: <img src="img/example.png">. This link will be based on your current location.
When your current location is http://example.com/ (index.html), then it will refer to http://example.com/img/example.png, where the file is probably located.
But when your location is http://example.com/management (management.html), it refers to http://example.com/management/img/example.png, which will return a 404.
Using the absolute path of this file will solve this problem. You can do this by putting a / in front of the relative path: <img src="/img/example.png">. Alternatively you could use a relative path in management.html like this: <img src="../img/example.png">.
I have a page asking for these files
<link rel="stylesheet" href="/vendor/css/style.css">
<script type="text/javascript" src="/vendor/js/app.js"></script>
and I've set up the express static route as follows
express = require 'express'
app = express()
app.use '/vendor/js', express.static './node_modules/framework/'
app.use '/vendor/css', express.static './otherFramework/'
app.get '/page/:num', (req, res) ->
page = parseInt req.params.num, 10
res.render 'list', #list is a jade file that extends a common layout.jade, the same as the '/' route
start: page
end: ++page
return
when I open the page '/' everything works fine, but now I want to implement another MVC-like route like '/page/:num', and express is asked this new route as base path for my requested external files, ex: (from the server log)
/page/1/vendor/css/style.css - 200
and this obviously doesn't work.
How can I tell express to search in the root? I tried to use a ~ before the path but it didn't work.
in the app.js (main file) file,before application routes, add these lines :
app.get('*/vendor/css/style.css', function (req, res) {
res.sendFile(__dirname + '/vendor/css/style.css');
});
app.get('*/vendor/js/app.js', function (req, res) {
res.sendFile(__dirname + '/vendor/js/style.js');
});
#akram-saouri 's answer was almost exact: I ended up using this configuration:
app.use '*/vendor/js', express.static './node_modules/framework/'
app.use '*/vendor/css', express.static './otherFramework/'
for all the app and it worked like a charm
I'm making some frontend experiments and I'd like to have a very basic webserver to quickly start a project and serve the files (one index.html file + some css/js/img files). So I'm trying to make something with node.js and express, I played with both already, but I don't want to use a render engine this time since I'll have only a single static file, with this code I get the html file but not the assets (error 404):
var express = require('express'),
app = express.createServer();
app.configure(function(){
app.use(express.static(__dirname + '/static'));
});
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
app.listen(3000);
Is there a simple way to do it (in one file if possible) or Express requires the use of a view and render engine ?
I came across this because I have a similar situation. I don't need or like templates. Anything you put in the public/ directory under express gets served as static content (Just like Apache). So I placed my index.html there and used sendfile to handle requests with no file (eg: GET http://mysite/):
app.get('/', function(req,res) {
res.sendfile('public/index.html');
});
Following code worked for me.
var express = require('express'),
app = express(),
http = require('http'),
httpServer = http.Server(app);
app.use(express.static(__dirname + '/folder_containing_assets_OR_scripts'));
app.get('/', function(req, res) {
res.sendfile(__dirname + '/index.html');
});
app.listen(3000);
this loads page with assets
You could use a solution like this in node.js (link no longer works), as I've blogged about before.
The summarise, install connect with npm install connect.
Then paste this code into a file called server.js in the same folder as your HTML/CSS/JS files.
var util = require('util'),
connect = require('connect'),
port = 1337;
connect.createServer(connect.static(__dirname)).listen(port);
util.puts('Listening on ' + port + '...');
util.puts('Press Ctrl + C to stop.');
Now navigate to that folder in your terminal and run node server.js, this will give you a temporary web server at http://localhost:1337
Thank you to original posters, but their answers are a bit outdated now. It's very, very simple to do. A basic setup looks like this:
const express = require("express");
const app = express();
const dir = `${__dirname}/public/`;
app.get("/", (req, res) => {
res.sendFile(dir + "index.html");
});
app.get("/contact", (req, res) => {
res.sendFile(dir + "contact.html");
});
// Serve a 404 page on all other accessed routes, or redirect to specific page
app.get("*", (req, res) => {
// res.sendFile(dir + "404.html");
// res.redirect("/");
});
app.listen(3000);
The above example is if you want to serve individual HTML files. If you were serving a single page JS app, this would work.
const express = require("express");
const app = express();
const dir = `${__dirname}/public/`;
app.get("*", (req, res) => {
res.sendFile(dir + "index.html");
});
app.listen(3000);
If you need to serve other static assets from within a folder, you can add something like this before you start defining the routes:
app.use(express.static('public'))
Let's say you have a js folder inside public like: public/js. You could include any of those files inside of your html files using relative paths. For example, let's say /contact needs a contact.js file. In your contact.html file, you can include the script as easy as:
<script src="./js/contact.js"></script>
Building off of that example, you can do the same with css, images etc.
<img src="./images/rofl-waffle.png" />
<link rel="stylesheet" href="./css/o-rly-owl.css" />
Hope this helps everyone from the future out.