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);
}
]);
Related
I just created a very simple landing page. I intended to practice my node skills and try to host the static website into my local server by using node. This is my file structure:
On my mac desktop. Inside NodeWebTest:
./assests
./css
./sass
index.html
But when I try to run it with my node code, my local server just running and cannot stop. What happen? How can I fix it?
var express = require('express');
var app = express();
var path = require('path');
app.use(express.static(__dirname + '/css'));
app.use(express.static(__dirname + '/assets'));
app.get('/', function(req, res) {
// res.sendFile(path.join(__dirname + '/index.html'));
res.writeHead(200, {"Content-Type": "./index.html"});
});
app.listen(3000);
I have a mean-stack application. By going to https://localhost:3000/#/home, it reads views/index.ejs. Here is the setting in app.js:
var app = express();
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(express.static(path.join(__dirname, 'public')));
app.all('/*', function(req, res, next) {
res.sendFile('index.ejs', { root: __dirname });
});
Actually, I don't use the feature of ejs in index.ejs. So now I want to use just a index.html rather than index.ejs.
I put the content of index.ejs in public/htmls/index.html and views/index.html. And here is the current setting in app.js:
var app = express();
// app.set('views', path.join(__dirname, 'views'));
// app.set('view engine', 'ejs');
app.use(express.static(path.join(__dirname, 'public')));
app.all('/*', function(req, res, next) {
res.sendFile('index.html', { root: __dirname });
// res.sendFile('index.html'); // does not work either
});
However, running https://localhost:3000/#/home returns
Error: No default engine was specified and no extension was provided.
Does anyone know how to fix it?
Edit 1: by following the answer of user818510, I tried res.sendFile('index.html', { root: path.join(__dirname, 'views') }); in app.js, it still can NOT find index.html.
Whereas, in routes/index.js, the following can find index.html, but it gives a warning express deprecated res.sendfile: Use res.sendFile instead routes/index.js:460:9.
var express = require('express');
var router = express.Router();
var path = require('path');
... ...
router.get('*', function(req, res) {
res.sendfile('./views/index.html'); // works, but a deprecation warning
// res.sendFile('index.html', { root: path.join(__dirname, 'views') }); does not work
});
It is really confusing...
If it's a single page mean application, then you only need to start express with static and put index.html in static/ dir :
Project layout
static/
index.html
server.js
server.js
'use strict';
var express = require('express');
var app = express();
app.use(express.static('public'));
var server = app.listen(8888, function () {
console.log("Server started. Listening on port %s", server.address().port);
});
Now you can call http://localhost:8888/#home
It looks like a problem with the path. Your index.html is located at public/htmls/index.html and views/index.html. Your root option in res.sendFile should be __dirname+/public/htmls/ or __dirname+/views
In your code, you are using the path:
res.sendFile('index.html', { root: __dirname });
Your app.js would be in the project root where you have public directory alongside at the same level. Based on your rootoption in res.sendFile, you would have to place index.html at the same level as your app.js.
You should change the root path in res.sendFile. Use:
res.sendFile('index.html', { root: path.join(__dirname, 'public', 'htmls') });
OR
res.sendFile('index.html', { root: path.join(__dirname, 'views') });
The above root is based on the path that you've mentioned in your question.
Here's the link to the docs:
http://expressjs.com/en/api.html#res.sendFile
Your no default engine error is probably because you have commented the line where you set the view engine to ejs but still have existing ejs views. Uncommenting that line with the root path change should solve your issue.
Do not serve static content from an application server.
Use a web server for that, and in production, a content delivery network like Akamai.
A content delivery network will charge you per bandwidth (e.g: 10 cents per Terabyte). Serving the equivalent of 10 cents in Akamai can cost you thousands of dollars using cloud instances.
In addition to that, your servers will have unnecessary load.
If you absolutely have to serve static content from your application servers, then put a reverse proxy cache like nginx, varnish or squid in front of your server. But that will still be very cost inefficient. This is documented in the express website.
This is common practice in every Internet company.
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');
});
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).
I don't understand whats going wrong here.
directory structure:
app/server.js
app/public/index.html
app/public/js/main.js
app/public/img/car.png
server.js
var fs = require('fs') ,express = require('express'),
app = express.createServer();
app.use(express.static(__dirname + "/public"));
app.get('/', function(req, res){
fs.readFile(__dirname + '/public/index.html', 'utf8', function(err, text){
res.send(text);
});
});
app.listen(8080, function(){
console.log('Server listening on %d', app.address().port);
});
main.js
var marker = new google.maps.Marker({
map:map,
position:coords,
icon: 'img/car.png'
});
erroroutput:
Failed to load resource: the server responded with a status of 404 (Not Found) http://localhost:8080/img/car.png
All my css files and js files load with no problem.
What am I doing wrong?
UPDATE
This was due to the file being named car.png.png
When browsing in windows, fileextensions were not visible so I was fooled into thinking the name was really car.png
Lesson learned!
Change this line
app.use(express.static(__dirname + "/public"));
To this
app.use('/public', express.static(__dirname + "/public"));
Try using an absolute path - /img/car.png