I am unable to load view using "$location.path"
Although my browser URLis getting updated but my content is not getting loaded. Here is the controller code:
var app= angular.module("LoginModule",[]);
app.controller("LoginController",['$scope','$http','$location',function($scope,$http,$location){
$scope.submitForm= function(valid){
if(valid){
$http.get('/admin/dashboard').success(function(data){
$location.path('dashboard');
});
}
};
}]);
It is changing my URL to "http://example.com/admin#/dashboard" for the same page.
My router file code is:
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/admin', function(req, res) {
res.render('admin/login', { title: 'Login' });
});
router.get('/admin/dashboard', function(req, res) {
//res.render('admin/dashboard', { title: 'Welcome to dashboard' });
res.send("success");
});
module.exports = router;
Please advise I am doing anything wrong.
Per the AngularJS docs at https://docs.angularjs.org/api/ng/service/$location :
Note: Path should always begin with forward slash (/), this method
will add the forward slash if it is missing.
so, you need to put the full value in there:
$location.path('/admin/dashboard');
instead of
$location.path('dashboard');
Related
Okay so this question originates from this post, which is also my question but sorta moved onto this problem.
Now the problem is, my angular app works but when it comes to Node routes, like /login, the browser thinks it's an Angular route. The browser does detect it as a Node route when I refresh the whole page but not when I am navigating the site once Angular routing has kicked in.
Long story short, here are my route files:
require('./routes/routes.js')(express, app);
require('./routes/default.js')(express, app);
routes.js file:
module.exports = function(express, app){
var router = express.Router();
router.get('/', function(req, res){
res.render('index');
});
router.get('/login', function(req, res){
if (req.isAuthenticated()){
res.render('index');
} else {
res.render('login');
}
});
default.js:
module.exports = function(express, app, passport, Promise){
var defaultRouter = express.Router();
defaultRouter.get('/*', function(req, res, next) {
res.render('./views/index.html');
});
};
Your help will be very much appreciated.
Thanks
I gave up on making this work on the root URL so I added /index to the baseURL like this:
index.html file:
<head>
<base href="/index/">
</head>
The, I added a catch all to the routes.js file, as below:
module.exports = function(express, app){
var router = express.Router();
router.get('*', function(req, res, next) {
if(req.url == '/' || req.url == '/login'){
next();
} else {
res.sendfile('./views/index.html');
}
});
router.get('/', function(req, res){
res.render('index');
});
router.get('/login', function(req, res){
if (req.isAuthenticated()){
res.render('index');
} else {
res.render('login');
}
});
With the angular file of course having this:
$locationProvider.html5Mode({
enabled: true,
requireBase: true
}).hashPrefix('');
And there. It works like a charm now.
I hope this helps whoever are in my shoes.
I am working on a site which is in Angular JS language. Now for website, I have to generate dynamic sitemaps and for this I used Node JS and created a xml.js route in node and wrote hello world.
Now the problem is, I am not able to use access this xml.js in angular site. Here is xml.js code :
var express = require("express");
var router = express.Router();
router.get("/test", function() {
console.log("hello world");
});
module.exports = router;
Here is server.js code :
var express=require('express');
var xml = require("./xml");
var app=express();
app.use('/xml',xml);
app.use('/',express.static('app'));
app.listen(9000) ;
Now whenever I try to access http://192.168.0.19:9000/xml/test I am being redirected to home page always.
Can someone help me out ?
You can try this code.This code work for me
You need to pass req and res parameter.
router.get('/', function (req, res) {
res.send('home page')
})
router.get("/test", function (req, res) {
console.log("hello world");
res.send('test page')
})
Is there a way to force the user to log in first in an app generated by the angular full stack yeoman ?
I tried to add the following code in the run part of app.js but was not successful
Auth.isLoggedIn(function(loggedIn) {
console.log(loggedIn);
if (!loggedIn) {
console.log("redirecting");
// event.preventDefault();
$state.go('login');
}
});
I found authentication controls in api index.js files but none for the / landing page ...
Thx
I did not use google as i should have !
To force authentication for a state, just add
authenticate: true
in the state (or all states in my case)
Without more code or information on which router you are using (generator-angular-fullstack supports both the default NgRouter and UIRouter) it is tough to give a complete answer. By your answer to your question I am assuming you have UI Router and have figured out how to do client side authentication within the generated fullstack code. However, you will also need to implement something similar to what they have done in their 'users' api to protect your api end points on the server side and return a 401/403 error.
'use strict';
var express = require('express');
var controller = require('./user.controller');
var config = require('../../config/environment');
var auth = require('../../auth/auth.service');
var router = express.Router();
router.get('/', auth.hasRole('admin'), controller.index);
router.delete('/:id', auth.hasRole('admin'), controller.destroy);
router.get('/me', auth.isAuthenticated(), controller.me);
router.put('/:id/password', auth.isAuthenticated(), controller.changePassword);
router.get('/:id', auth.isAuthenticated(), controller.show);
router.post('/', controller.create);
module.exports = router;
In the above code (which can be found by navigating to the server folder, then the api folder, then the user folder and looking at index.js) you will see that they are calling a couple of functions.
They are calling auth.hasRole('admin') and auth.isAuthenticated().
Those are functions which can be found in the server side auth/role service under the folder auth and in the auth.service.js file.
function hasRole(roleRequired) {
if (!roleRequired) throw new Error('Required role needs to be set');
return compose()
.use(isAuthenticated())
.use(function meetsRequirements(req, res, next) {
if (config.userRoles.indexOf(req.user.role) >= config.userRoles.indexOf(roleRequired)) {
next();
}
else {
res.status(403).send('Forbidden');
}
});
}
I think it is important to understand how this is working on the server side also. So, if you navigate to localhost:9000/admin and open console you will see that there is a 401 or 403 error depending on whether or not you are logged in and/or logged in as an admin user.
Just Paste authenticate:true on main.js
angular.module('testcesarApp')
.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'app/main/main.html',
controller: 'MainCtrl',
authenticate:true
});
});
This is my router file:
it's nested inside a require.js block and configured to work with Jade templates
define([
'./app',
'angular.uirouter'
], function(app, angularUIRouter) {
"use strict";
// ROUTES
app.config(['$stateProvider', '$urlRouterProvider', '$locationProvider', function($stateProvider, $urlRouterProvider, $locationProvider) {
// loads url from the index
$urlRouterProvider.otherwise('/');
$locationProvider.html5Mode(true);
$stateProvider
.state('dashboard', {
url:'/dashboard',
views: {
'core' : {
templateUrl: '/articles/dashboard'
}
}
})
}]);
});
And this is my Express.js router file:
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res) {
res.render('main', {
title: 'Express'
});
});
router.get('/dashboard', function(req, res) {
console.log("/dashboard requested");
});
router.get('/articles/:name', function (req, res) {
var name = req.params.name;
res.render('articles/' + name);
});
module.exports = router;
When I go to localhost:3000/dashboard, it's making a GET request to the server. How do I configure Angular UI Router to handle GET requests instead of the server?
Note: I can still go to localhost:3000/articles/dashboard and see the dashboard. Also,
a(ui-sref="dashboard")
loads the dashboard correctly.
Neither angular nor ui router can not handle server GET. Angular $locationProvider html5Mode solves only client-side setting - url does not contain # and location controls also path part in URL.
Html5 mode requires server side configuration. Every requests must return application entry point - usually index.html.
For example
router.get('/dashboard', function(req, res) {
res.sendfile('path-to/index.html');
});
So, I am using mean.io and for some reason, my routes.js never hits my 'index.all' method, or the 'exports.all' function, even though I require the functions from the server-side controller. Also, my routing is done using angular-ui-router. Does anybody know how to call a backend method from routing in MEAN.IO? I keep using:
'use strict';
module.exports = function(System, app, auth, database) {
// Home route
var index = require('../controllers/index');
app.route('/test').get(index.all);
app.route('/')
.get(index.render);
};
I would like to hit 'index.all' but even if I navigate to /test, it still gets
index.render. Does anybody know why?
Here is the controllers file:
'use strict';
var mean = require('meanio');
var mongoose = require('mongoose');
var Composition = mongoose.model('Composition');
exports.render = function(req, res) {
console.log(req.user);
var modules = [];
// Preparing angular modules list with dependencies
for (var name in mean.modules) {
modules.push({
name: name,
module: 'mean.' + name,
angularDependencies: mean.modules[name].angularDependencies
});
}
function isAdmin() {
return req.user && req.user.roles.indexOf('admin') !== -1;
}
// Send some basic starting info to the view
res.render('index', {
user: req.user ? {
name: req.user.name,
_id: req.user._id,
username: req.user.username,
roles: req.user.roles
} : {},
modules: modules,
isAdmin: isAdmin,
adminEnabled: isAdmin() && mean.moduleEnabled('mean-admin')
});
};
exports.all = function(req, res) {
console.log(req.user);
Composition.find({user: req.user}, 'title description').sort('-created').populate('user', 'name username').exec(function(err, compositions) {
if (err) {
return res.jsonp(500, {
error: 'Cannot list the compositions'
});
}
res.jsonp(compositions);
});
};
Is this a front-end or backend problem? Thanks for any advice that might be helpful.
You are navigating. So are you hitting the link in the browser url? Then you should try localhost:3000/test instead of localhost:3000/#!/test.
The urls of the form localhost:3000:/#!/<something> are angular routes. Look up angular routing and views. It is better to use angular views than server side rendering. Do angular routing for test and add a view corresponding to it. Fetch the dynamic data in the view using the regular $http.get calls.
Check this tutorial for routing and adding views in angular