Using Express, I run the index.html file but cannot get the css, js or images to link up correctly. No images showing, css and js not linking.
<link rel="stylesheet" type="text/css" href="css/main.css">
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/main.js"></script>
img/logo.png
I have the following directory structure:
root
app.js
package.json
node_modules
assets
img
css
js
templates
theme1
css
fonts
img
js
index.html
about.html
services.html
news.html
contact.html
In app.js:
var express = require('express');
var app = express();
var path = require('path');
app.get('/', function(req, res) {
//res.sendFile(path.join(__dirname + '/assets/templates/theme1/index.html'));
});
app.get('/about/', function(req, res) {
res.sendFile(path.join(__dirname + '/assets/templates/theme1/about.html'));
});
app.get('/services/', function(req, res) {
res.sendFile(path.join(__dirname + '/assets/templates/theme1/services.html'));
});
app.get('/services/', function(req, res) {
res.sendFile(path.join(__dirname + '/assets/templates/theme1/news.html'));
});
app.get('/contact/', function(req, res) {
res.sendFile(path.join(__dirname + '/assets/templates/theme1/contact.html'));
});
app.listen(3000);
need better understanding of app.get and app.use as well as res.sendFile
Thanks all
So, it's not working because you're not telling Express to serve the files you want (the js and css and so on).
First you want to setup a static route using the static middleware:
app.use(express.static(__dirname + '/assets'));
At that point, everything in the 'assets' directory will be served relative to your root URL. So /img/someimage.jpg is the correct URL for it.
Related
I am trying to create an express application that works with React and React-router on the front end. So I'm loading the index.html file and let react router handle the rest of the routing. But when refreshing on a page with a react router url that doesn't have an express route I obviously get the message {cannot GET .....}. So i added a fallback route after all my routes to always return index.html when there is no route.
So now I have routes to "/api/...", "/" and "*", I am also serving static files from "/public/build" and "/app/src/static/". When calling the "/" everything works great, when calling the "*" the index.html gets loaded, but the index.js and styles.css files are both loaded with the content from index.html. So my browser gets a styles.css file with a bunch of html in it whereas when using the "/" route the .js and .css files get loaded correctly.
So navigating to "/" loads the index page correctly with all the static files. I can then use my react-router-dom NavLink to navigate to difirent views without making a request back to the server. But when i try to load any react-router-dom page directly I get my index.html but my index.js has the same contents as index.html, same for styles.css
My code:
const app = express();
app.use(bodyParser.urlencoded({ extended: true}));
app.use(bodyParser.json());
passportConfig(passport);
app.use(passport.initialize());
app.use(passport.session());
app.use('/api/user', userRoutes);
app.use('/api', championRoutes);
app.use('/public/build', express.static(__dirname + '/public/ReactApp/build'));
app.use("/app/src/static/image", express.static(__dirname + '/public/ReactApp/src/static/image'));
app.use("/app/src/static/style", express.static(__dirname + '/public/ReactApp/src/static/style'));
app.get('/', (req, res) => {
res.sendFile(path.resolve(__dirname, '..', 'index.html'));
});
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, '..', 'index.html'));
});
app.listen(8080, () => {
console.log('started on port 8080');
});
The userRoutes and championRoutes variables both contain an express.Router object that has a few routes set.
Edit:
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<link href="app/src/static/style/styles.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
<div id="app"></div>
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="public/build/index.js"></script>
</body>
</html>
<script src="public/build/index.js"></script>
This means that the location is relative to the current path, ie, if you are at http://somedomain.com/page2, the path to the index.js will be http://somedomain.com/page2/public/build/index.js (which in your case will serve the index.html file).
To specify a relative path from the base of your url instead, start the path with a /:
<script src="/public/build/index.js"></script>
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 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 just built a Webpack project:
static/ // where I have the js and css file
index.html // the main file
And placed it inside the public/ folder in an Express setup:
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.sendfile('public/index.html')
});
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
But I get these errors:
http://localhost:3000/static/app.79c874fce37c5d0a32117271eb04a7f8.css
http://localhost:3000/static/app.57fd4b2335b940c7b8d1.js 404 (Not Found)
This is the content of index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8>
<title>istaging-viewer</title>
<link href=/static/app.79c874fce37c5d0a32117271eb04a7f8.css rel=stylesheet>
</head>
<body>
<div id=app>
<script src=/static/app.57fd4b2335b940c7b8d1.js></script>
</div>
</body>
</html>
(Those files exist in the /static/ directory).
How should I change the Express code so Express can find those files?
EDIT: I tried this ...
app.get('/', function (req, res) {
res.sendfile('static/index.html')
});
... but I'm still getting this error:
GET http://localhost:3000/static/app.79c874fce37c5d0a32117271eb04a7f8.css
localhost/:1 GET http://localhost:3000/static/app.57fd4b2335b940c7b8d1.js 404 (Not Found)
EDIT 2:
I tried this to serve the static files:
app.use(express.static('static'));
I still get the same errors:
GET http://localhost:3000/static/app.79c874fce37c5d0a32117271eb04a7f8.css
localhost/:1 GET http://localhost:3000/static/app.57fd4b2335b940c7b8d1.js 404 (Not Found)
So long as your app/main js file is in the same folder as your index.html, then change
app.get('/', function (req, res) {
res.sendfile('public/index.html')
});
to
app.get('/', function (req, res) {
res.sendfile('index.html')
});
Ideally, however, your file structure should look something like:
app.js
static/
index.html
js/
css/
img/
that way, you'd reference it this way
app.get('/', function (req, res) {
res.sendfile('static/index.html')
});
I've configured express as follows:
var express = require('express');
var app = express();
app.get('/', function(req, res) {
res.sendfile(__dirname + '/3in1/src/index.html');
});
app.get('/index.html', function(req, res) {
res.sendfile(__dirname + '/3in1/src/index.html');
});
/* serves all the static files */
app.use(express.static(__dirname + '/3in1/src/'));
var port = process.env.PORT || 80;
app.listen(port, function() {
console.log("Listening on " + port);
});
I have my css in a file under the folder
/3in1/src/css/
Which all make it to the browser OK. The problem is when the request is made to my javascript files, which, are located throughout the following folder like so:
/3in1/bower_components/library-name/library.js
/3in1/bower_components/library-two/library_two.js
etc...
etc..
etc.
The problem is I get a 404. The links in my index look something like this:
<script type="text/javascript" src="../bower_components/PreloadJS/lib/preloadjs-0.4.1.combined.js"></script>
<script type="text/javascript" src="../bower_components/jquery/dist/jquery.js"></script>
<script type="text/javascript" src="../bower_components/jquery-mousewheel/jquery.mousewheel.js"></script>
What am i doing wrong? I thought that it would recognize the relative paths I'm using, i.e. "../" but I thought wrong, I guess! What is the correct way to do this?
The solution for this simple example was to just add the following line of code:
app.use('/bower_components', express.static(__dirname + '/3in1/bower_components/'));