Nodejs / Expressjs Cannot link to css file - node.js

I am trying out node / express js and created a little web project.
I have the views in root /views directory
so:
root
/views
/css
I've added this to /views/index.html file:
<link rel="stylesheet" type="text/css" href="css/style.css" />
And this is my server.js file code:
var express = require("express");
var app = express();
var router = express.Router();
var path = __dirname + '/views/';
var path = __dirname + '/css/'; //Not working
router.use(function (req,res,next) {
console.log("/" + req.method);
next();
});
router.get("/",function(req,res){
res.sendFile(path + "index.html");
});
router.get("/about",function(req,res){
res.sendFile(path + "about.html");
});
router.get("/contact",function(req,res){
res.sendFile(path + "contact.html");
});
app.use("/",router);
app.use(express.static('public'));
app.use("*",function(req,res){
res.sendFile(path + "404.html");
});
app.listen(3000,function(){
console.log("Live at Port 3000 - http://localhost:3000");
});
How can I get it to read my css files?

To serve static files using Express.JS, use its built-in express.static middleware.
Assuming following directory structure:
root/
server.js
css/
styles.css
All you need is the following code in your server.js file:
var express = require('express');
var app = express();
// key line! - serve all static files from "css" directory under "/css" path
app.use('/css', express.static('css'));
app.listen(3000, function() {
console.log('Live at Port 3000 - http://localhost:3000');
});
To make styles.css available under localhost:3000/css/styles.css address (and analogically for all other files kept in css directory).

Related

Run HTML file on HTTPS local server [duplicate]

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' })

Is index.html name is predefined in Express?

index.html login.html app.js
I have two files named index.html & login.html,whenever I start server with index.html file it load ,but when I route to the login then login.html don't work,so then after I interchange code in files then login.html files load but as index.html
Try this code and see if it works, not much information is provided in the question.
Maybe show your code.
var express = require('express');
var PORT = 3400;
var path = require('path');
var app = express();
app.get('/login',function(req,res){
req.sendFile(path.join(__dirname + '/login.html'));
})
app.get('/index',function(req,res){
req.sendFile(path.join(__dirname + '/index.html'));
});
app.listen(PORT,function(){
console.log('Serving on PORT' + PORT);
})

how to access images on disk on localhost and access via url on website [duplicate]

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' })

Express app not rendering my react components

I'm building a Express app using React. I start my server, go to localhost and I see a blank page, when I check the developer tools on chrome it shows me that my js file is plain HTML. Why is that?
This is my server.js:
var express = require('express');
var app = express();
var port = process.env.NODE_ENV || 3000;
app.get('*', function(req, res) {
res.sendFile(__dirname + '/public/views/index.html');
});
app.listen(port, function() {
console.log('Listening to http://localhost:' + port);
});
This is my app.js:
var React = require('react'),
ReactDOM = require('react-dom');
var App = React.createClass({displayName: "App",
render () {
return (
React.createElement("h1", null, "Hello World!!!!!")
)
}
});
ReactDOM.render(React.createElement(App, null), document.getElementById('main-app'));
My index.html:
<body>
<div id="main-app"></div>
</body>
<script src="public/assets/dist/javascripts/app.js"></script>
This is what I see on developer tools:
image
The problem is that whatever file you are requesting to your server you are always returning index.html.
So when you go to http://localhost:3000/ you get index.html
The problem is that your index.html then requests public/assets/dist/javascripts/app.js but you still return index.html as if it was app.js.
You need to update your route so it returns the file that was requested.
I think adding this to your server.js might fix it.
app.use(express.static(__dirname + '/public'));
Instead of
app.get('*', function(req, res) {
res.sendFile(__dirname + '/public/views/index.html');
});

Nodejs & Angularjs, Clean urls

How do I setup node/angular to have the index.html/app run at example.com rather than example.com/app/index.html#/home
I tried putting the index.html at the root of the node server but that still leaves the url as example.com/index.html#/home
What you need is to enable html5mode. It's documentation and considerations can be found here.
Here's an example taken from Brian Ford:
angular.module('myApp', ['myApp.filters', 'myApp.services', 'myApp.directives']).
config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
// configure $routeProvider, then...
$locationProvider.html5Mode(true);
}
]);
The angular-ui framework has example configuration for wiring this up to express.js:
var express = require('express');
var app = express();
app.use('/js', express.static(__dirname + '/js'));
app.use('/dist', express.static(__dirname + '/../dist'));
app.use('/css', express.static(__dirname + '/css'));
app.use('/partials', express.static(__dirname + '/partials'));
app.all('/*', function(req, res, next) {
// Just send the index.html for other files to support HTML5Mode
res.sendfile('index.html', { root: __dirname });
});
app.listen(3006); //the port you want to use
In Brian's article, you don't have to manually map the static asset folders because his example delivers the single index.html, maps partials to /partials/:name, then interacts with /api/*
If you are using Yoeman, or grunt build on your NODEJS server.
You can simple add new file server.js into root folder, and if your app folder is inside and your root folder.
var express = require('express');
var app = express();
app.use(express.static(__dirname + "/app"));
app.all('*', function(req, res, next) {
// Just send the index.html for other files to support HTML5Mode
res.sendFile('/app/index.html', { root: __dirname });
});
var port = 1337;
app.listen(port); //the port you want to use
console.log('Server running at localhost:' + port);
And make sure you have enabled HTML5 mode inside your AngularJs config
angular.module('yourApp')
.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
$routeProvider
.when('/some', {
templateUrl: '../templates/some.html'
})
.otherwise({redirectTo: '/'});
//enabling HTML5 mode
$locationProvider.html5Mode(true);
}
]);

Resources