CSS styling will not appear with my HTML when running in Node.
Directory:
Login_Page_V2.html
Login_Page_V1.js
public
-css
-style.css
My server code:
var express = require('express');
var session = require('express-session');
var bodyParser = require('body-parser');
var path = require('path');
var app = express();
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', function(request, response) {
response.sendFile(path.join(__dirname + '/Login_Page_V2.html'));
});
HTML code:
link rel="stylesheet" type="text/css" href="./public/css/styleProject.css"/
You need to serve your static middleware at /public.
app.use('/public', express.static(path.join(__dirname, 'public')));
Without adding that middleware path, express is looking for the uri of /public/css/styleProject.css inside the public directory (essentially, trying to reference the file at ${__dirname}/public/public/css/styleProject.css). By specifying the path for your static middleware, you avoid this duplication and improve performance since only uris prefixed with /public/ will be looked up on the file system.
Related
I want to serve index.html and /media subdirectory as static files. The index file should be served both at /index.html and / URLs.
I have
web_server.use("/media", express.static(__dirname + '/media'));
web_server.use("/", express.static(__dirname));
but the second line apparently serves the entire __dirname, including all files in it (not just index.html and media), which I don't want.
I also tried
web_server.use("/", express.static(__dirname + '/index.html'));
but accessing the base URL / then leads to a request to web_server/index.html/index.html (double index.html component), which of course fails.
Any ideas?
By the way, I could find absolutely no documentation in Express on this topic (static() + its params)... frustrating. A doc link is also welcome.
If you have this setup
/app
/public/index.html
/media
Then this should get what you wanted
var express = require('express');
//var server = express.createServer();
// express.createServer() is deprecated.
var server = express(); // better instead
server.configure(function(){
server.use('/media', express.static(__dirname + '/media'));
server.use(express.static(__dirname + '/public'));
});
server.listen(3000);
The trick is leaving this line as last fallback
server.use(express.static(__dirname + '/public'));
As for documentation, since Express uses connect middleware, I found it easier to just look at the connect source code directly.
For example this line shows that index.html is supported
https://github.com/senchalabs/connect/blob/2.3.3/lib/middleware/static.js#L140
In the newest version of express the "createServer" is deprecated. This example works for me:
var express = require('express');
var app = express();
var path = require('path');
//app.use(express.static(__dirname)); // Current directory is root
app.use(express.static(path.join(__dirname, 'public'))); // "public" off of current is root
app.listen(80);
console.log('Listening on port 80');
express.static() expects the first parameter to be a path of a directory, not a filename. I would suggest creating another subdirectory to contain your index.html and use that.
Serving static files in Express documentation, or more detailed serve-static documentation, including the default behavior of serving index.html:
By default this module will send “index.html” files in response to a request on a directory. To disable this set false or to supply a new index pass a string or an array in preferred order.
res.sendFile & express.static both will work for this
var express = require('express');
var app = express();
var path = require('path');
var public = path.join(__dirname, 'public');
// viewed at http://localhost:8080
app.get('/', function(req, res) {
res.sendFile(path.join(public, 'index.html'));
});
app.use('/', express.static(public));
app.listen(8080);
Where public is the folder in which the client side code is
As suggested by #ATOzTOA and clarified by #Vozzie, path.join takes the paths to join as arguments, the + passes a single argument to path.
const path = require('path');
const express = require('express');
const app = new express();
app.use(express.static('/media'));
app.get('/', (req, res) => {
res.sendFile(path.resolve(__dirname, 'media/page/', 'index.html'));
});
app.listen(4000, () => {
console.log('App listening on port 4000')
})
If you have a complicated folder structure, such as
- application
- assets
- images
- profile.jpg
- web
- server
- index.js
If you want to serve assets/images from index.js
app.use('/images', express.static(path.join(__dirname, '..', 'assets', 'images')))
To view from your browser
http://localhost:4000/images/profile.jpg
If you need more clarification comment, I'll elaborate.
use below inside your app.js
app.use(express.static('folderName'));
(folderName is folder which has files) - remember these assets are accessed direct through server path (i.e. http://localhost:3000/abc.png (where as abc.png is inside folderName folder)
npm install serve-index
var express = require('express')
var serveIndex = require('serve-index')
var path = require('path')
var serveStatic = require('serve-static')
var app = express()
var port = process.env.PORT || 3000;
/**for files */
app.use(serveStatic(path.join(__dirname, 'public')));
/**for directory */
app.use('/', express.static('public'), serveIndex('public', {'icons': true}))
// Listen
app.listen(port, function () {
console.log('listening on port:',+ port );
})
I would add something that is on the express docs, and it's sometimes misread in tutorials or others.
app.use(mountpoint, middleware)
mountpoint is a virtual path, it is not in the filesystem (even if it actually exists). The mountpoint for the middleware is the app.js folder.
Now
app.use('/static', express.static('public')`
will send files with path /static/hell/meow/a.js to /public/hell/meow/a.js
This is the error in my case when I provide links to HTML files.
before:
<link rel="stylesheet" href="/public/style.css">
After:
<link rel="stylesheet" href="/style.css">
I just removed the static directory path from the link and the error is gone. This solves my error one thing more don't forget to put this line where you are creating the server.
var path = require('path');
app.use(serveStatic(path.join(__dirname, 'public')));
You can achieve this by just passing the second parameter express.static() method to specify index files in the folder
const express = require('express');
const app = new express();
app.use(express.static('/media'), { index: 'whatever.html' })
In this code I'm calling an html file into app.js, the css style is not applied to the html but when I open the html path alone without the app.js the style is applied, here's the code:
const express = require("express");
const bodyParser = require("body-parser");
const ejs = require("ejs");
const mongoose = require('mongoose');
const app = express();
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(express.static("public"));
mongoose.connect("mongodb://localhost:27017/aqeldb1", {useNewUrlParser: true});
app.route("/order")
.get(function(req, res){
res.sendFile(__dirname + "/ordernow.html");
});
app.listen(3000, function() {
console.log("Server started on port 3000");
});
Use in your main .js file:
app.use('/css',express.static(__dirname +'/css'));
use in you main .html file:
<link rel="stylesheet" type="text/css" href="css/style.css" />
Please keep .css files in the public folder
You need to set as static the directory where the .css files are or /index.html won't be able to access them when loaded through the express server.
app.use(express.static("directory/that/you/want/to/be/publicly/accessible")); <-- here you keep .css, and clientside .js files.
You could also put the .css files in the public folder if you don't want to add another static directory. A good approach is to make all the directories that contain the view files (.html, .css, .js) static.
Try to apply app.use(express.static('public'));
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
here is a list of folders and files i have
public__
|_generate-todo.js
|_index.js
|_style.css
views__
|_404
|main
users-data.json
server.js
Problem 1: I have done with view now i want to assign public folder style sheet and js files to my main handlebar page to generate better layout
problem 2: I have to fill my main handle drop down select list with json data in user-data.json file
what i done:
var path = require('path');
var express = require('express');
var exphbs = require('express-handlebars');
var app = express();
var usersData = require('./users-data');
var port = process.env.PORT || 3000;
// Use Handlebars as the view engine for the app.
app.engine('handlebars', exphbs({ defaultLayout: 'main' }))
app.set('view engine', 'handlebars');
// Define the port to run on
app.set('port', 3000);
app.get('/', function (req, res) {
res.render('index-page');
});
app.use(function(req, res) {
res.redirect('404-page');
});
var server = app.listen(app.get('port'), function() {
var port = server.address().port;
console.log('Magic happens on port ' + port);
});
anybody help me with these problems
The following answer relates to a previous version of the question.
Here you can see the original question
Solution Problem 1:
You have to serve your /public folder with express.
You can do it with the following code:
app.use(express.static(path.join(__dirname, '/public')));
Then you can add your css an js files from your public directory as usual. (Don't use /public in your href or src statement.)
So you can add this to your html file(s):
<link rel="stylesheet" href="/style.css" type="text/css">
<script src="/index.js" type="text/javascript"></script>
<script src="/generate-todo.js" type="text/javascript"></script>
Lookup express.static() docs for reference: express.static() documentation
Solution Problem 2:
You have already a require statement for your json file in your server.js:
var usersData = require(./users-data.json);
You can pass it to your template in the res.render() method:
// pass a local variable to the view
res.render('your-template', { usersData: usersData });
Now you can use it as usersData in your template on your dropdown-select. (e.g. {{ usersData.something }})
See express.js res.render() documentation for reference.
I am running a NodeJS server which uses a catchall route to serve a file 'index.html'. In that file, I am linking to a javascript file in the same directory. That javascript file is not being correctly loaded. The error in my console reads 'Uncaught SyntaxError: Unexpected Token <', which after researching seems to mean that the path to my JS file is incorrect. However, the js file is located in the same directory as 'index.html', and I am referencing it like so which should be correct?
Here is my code
server.js
var express = require('express');
var app = express();
var config = require('./config');
var apiRouter = express.Router();
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var User = require('./app/models/User');
var jwt = require('jsonwebtoken');
var path = require('path');
//Set the public folder
app.use(express.static('/public'));
//Allows us to parse POST data.
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
mongoose.connect(config.db);
var apiRouter = require('./app/routes/api')(app, express);
app.use('/api', apiRouter);
//MEAN apps use a catchall after any routes created by Node.
app.get('*', function(req, res) {
res.sendFile(path.join(__dirname, 'public/app/views/index.html'));
});
app.listen(1337);
console.log('Server started at ' + Date());
public/app/views/index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="./test.js"></script>
<head>
<body>
<h1>Served by node + express.</h1>
</body>
</html>
public/app/views/test.js
console.log('test.js loaded');
You should set your static folder like this
app.use(express.static(__dirname + '/public'));
Also, your html file will look inside the /public folder itself for your script file. You'll need to give your index.html file the right path to your script file.
<script src="/app/views/test.js"></script>
Here's what's happening:
The browser requests /, which is responded to by your catchall route, so it gets back index.html.
The browser then sees a script in the html at ./test.js, so the browser then interprets that as /test.js and makes a request for that. The express.static middleware looks up public/test.js, which does not exist, so it passes execution to the next defined route that matches the request, which is your catchall route. This means html is sent for the javascript file, hence the error that you see.
So to fix this, you need to change ./test.js to the actual relative path (./app/views/test.js) or use an absolute path (/app/views/test.js) to make sure the correct path is always used, no matter what the current path is.
Additionally, you will need to change this:
app.use(express.static('/public'));
to something like this:
app.use(express.static(__dirname + '/public'));
Otherwise the express.static middleware will look for a directory named public off the root of your filesystem and you will have the same problem with the catchall route serving html for your javascript file request.