I have an AngularJS app on a NodeJS server with ExpressJS. Now I am serving an Angular app as static files:
app.use(express.static(__dirname + '/app'));
But in navigation, I have a # sign:
http://127.0.0.1:8080/#/queryes
To solve this problem, I put this code in the Angular Router:
$locationProvider.html5Mode(true);
But now I can't get partial views. How do I mix Angular Routes with ExpressJS?
In order to use AngularJS html5mode along with Express, you must serve "index.html" for all requests to leave all routing up to AngularJS. I had this same problem a while back.
So first, you declare all API endpoint routes, any static file directories (CSS, JS, partials, etc), and then serve index.html for all remaining requests. For example:
// serve all asset files from necessary directories
app.use("/js", express.static(__dirname + "/app/js"));
app.use("/img", express.static(__dirname + "/app/img"));
app.use("/css", express.static(__dirname + "/app/css"));
app.use("/partials", express.static(__dirname + "/app/partials"));
app.use("/templates", express.static(__dirname + "/app/templates"));
// any API endpoints
app.post('/api/v1/auth/login', routes.auth.login);
// serve index.html for all remaining routes, in order to leave routing up to angular
app.all("/*", function(req, res, next) {
res.sendfile("index.html", { root: __dirname + "/app" });
});
Related
I have web application which is developed using ejs + angularJs 1.0 and running in node server. Since these ejs + angular provides only static files, I want to make my app running in webserver. Currently the URL mapping is done in node app.js, hence if we load the URL it renders the html from the ejs. For more information, I have added node app.js configuration:
app.set('title', wsConfig.title);
app.use(bodyParser.json());
app.engine('.html', ejs.__express);
app.set('view engine', 'ejs');
app.use(express.static('./public'));
app.set('views', path.join(__dirname, 'public')); // Set the views path
app.use(function(req, res, next) {
if (req.url.substr(-1) == '/' && req.url.length > 1)
res.redirect(301, req.url.slice(0, -1));
else
next();
});
app.get('/', function(req, res) {
res.render('login', { title: wsConfig.title });
});
app.get('/home', function(req, res) {
res.render('index', { title: wsConfig.title });
});
Hence I need to build a dist folder with js and rendered ejs files instead using node server for rendering. So that I will deploy this dist directory in web server. I thought of using webpack to accomplish this. Please give our suggestions.
I am using angular on the front end and express js MongoDB on the backend, in server.js file of express application I am listening on port 3000
var server = app.listen(3000, function () {
console.log('Server listening at http://' + server.address().address + ':' + server.address().port);
});
What I want is when I hit localhost:3000 my HTML page in angular js application should get render, which I achieved using
app.get('/', function (req, res) {
res.sendfile(__dirname + '/app/userlogin/userlogin.html');
});
When I hit localhost:3000 my HTML page is getting render but it is not including bootstrap files I am getting error 404 for scripts and links which I am adding in head tag but intelligence of vs2015 providing those bootstrap script files when I am trying to add them in my HTML, Following is my project structure and I have placed my bootstrap js and CSS files respectively in app -> js and app -> CSS
You need a public_static folder containing all your frontend code.
The express app should serve it with express.static('')
server.js
app.use(express.static('public_static'));
Directory Structure
-- server.js
-- public_static
-- index.html ( Rename your userlogin.html )
-- css
-- JS ( Angular files )
--- controllers
--- directives
--- services
My AngularJS application won't route to /login when accessing /login directly. It will route to /login if I first access / then route from / to /login.
It is working on my local environment but not with Heroku servers. Are there some settings I have to configure on the Heroku server?
I am using angular-ui-router to route to different states throughout my application.
My app.js config snippet looks like this:
angular.module('app', [
angularUiRouter
])
.config(($stateProvider) => {
"ngInject";
$stateProvider
.state("home", {
url: "/",
template: "<home></home>"
})
.state("login", {
url: "/login",
template: "<login></login>"
});
})
Answering my own question.
Since the setup on this application is using MEAN stack, we have to also add routing from server side to client.
For all templates in AngularJS there has to be a routing from Express to AngularJS to index.html
for all templates and routings created in angular we need to get the request and send index.html in response
when we use angularjs stateProvider to route in Angularjs.., we have to also add routing to /dist/index.html from server side.
$locationProvider.html5Mode(true).hashPrefix('!'); has to be defined in app.js on AngularJS side
A snippet of my Server.js file:
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/dist'));
app.get('/', function(req, res){
res.sendFile(__dirname + '/dist/index.html');
});
app.get('/login', function(req, res){
res.sendFile(__dirname + '/dist/index.html');
});
I'm sorry I'm reasonably new to node. I've been stuck on this for a couple hours.
server.js
app.use(express.static(__dirname + "/public"));
app.get('/', function(req, res){
res.sendFile(path.resolve(templatesPath + 'index.html'));
});
app.get('*', function(req, res){
res.sendFile(path.resolve(templatesPath + 'index.html'));
});
index.html is an Angular application. I have the first level of routes working fine using Angular's HTML5 routes eg. "http://lh:3000/staff" or "http://lh:3000"
but if I add another level or route parameters, e.g. "http://lh:3000/staff/" or "http://lh:3000/staff/test" Express seems to ignore express.static and instead uses the get wildcard to turn all my files into index.html so my page breaks.
Thanks for your help answerers
In secondary routes, it was loading assets referenced in index.html, relative to the secondary route. My temp solution is to add:
app.use('/files/',express.static(path.join(__dirname + "/public")));
but I realise now it is better to change my solution.
are staff/test, static assets sitting inside your assets folder?
If they are static assets, there must be a file in the path staff/test inside your assets folder.
if they are not static assets and they are dynamic content, consider using express.router,make a router for staff and add it as,
var staff = express.Router();
staff.use('/staff', staff)
//this is route handler for /staff/test
staff.post('/test', function(req, res, next){
res.json(some-json-content)
})
try this:
app.get('*/*', function(req, res){
res.sendFile(path.resolve(templatesPath + 'index.html'));
});
I am trying to deploy my angular app to heroku. It runs fine locally.
Directory:
nice-notes
controllers
api.js
index.js
Model
model.js
public
main.js
main.css
views
index.jade
layout.jade
payment.jade
app.js
package.json
Procfile
node_modules
My app.js looks like so:
app.set('view engine', 'jade');
app.set('views', __dirname + '/views');
app.use(express.static(__dirname + '/public'));
app.use(bodyParser.urlencoded({extended: false}));
app.get('/', indexController.index);
app.get('/payment', indexController.payment);
app.get('/api/notes', apiController.get);
app.post('/api/notes', apiController.noteUpdate);
My controller:
var Note = require('../Model/model')
var indexController = {
index: function(req, res) {
res.render('index');
},
payment: function(req, res) {
res.render('payment');
}
}
module.exports = indexController;
I have tried using this instead, but 'path' is not defined.
app.set('views', path.join(__dirname, 'views'));
All my base code is identical to my other angular apps, apart from the fact that I'm not injecting any templates here (using ng-view).
I have tried changing the file paths and other potential solutions to no avail.
The problem was that I had changed some filenames (capitalising the first letter), and then changed it back, but it never logged it.
Typing
heroku run 'ls -al'
into the shell creates a one-off dyno and displays the file-system as heroku sees it.
This is the thread that solved my problem:
Heroku Cannot find module