I am working on a personal project for a photography web application.
Still very new to node.js and express.
The previous ASP.Net MVC app I built for this application used a SQL database to index photos and auto-generate the neccesary photo gallery markup.
node-gallery
seemed like a good candidate to remove the db dependency.
However I seem to be confused as to how Express middleware works.
var nodeGallery = require('node-gallery');
//
//
app.use('/', new nodeGallery({
staticFiles : 'public/photos/slideshow',
urlRoot : 'photos/slideshow',
render : false
}), function(req, res, next){
rerurn res.render('index',{slideshow:req.data});
});
app.use('/portfolio', new nodeGallery({
staticFiles : 'public/photos/portfolio',
urlRoot : 'portfolio',
render : false
}), function(req, res, next){
console.log(req.data);
return res.render('portfolio',{portfolio:req.data});
});
I am wanting to use the node-gallery middleware with different properties for two pages (the front with a slideshow and the main gallery). However the last properties set are always used regardless of route.
Using express.Router and specifying a route which uses the middleware also appears to not work.
It seems like I am missing something basic here. Any suggestions would be appreciated.
var nodeGallery = require('node-gallery');
Think of this as creating a class/obj of node gallery.
Then in your first route you set its properties as:
new nodeGallery({
staticFiles : 'public/photos/slideshow',
urlRoot : 'photos/slideshow',
render : false
})
but in the second route you overwrite nodeGallery with a second set of properties:
new nodeGallery({
staticFiles : 'public/photos/portfolio',
urlRoot : 'portfolio',
render : false
})
The problem is you are using the same instance of nodeGallery, to define to sets of different properties.
Solution:
1. Create an object of multiple node-galleries i.e:
var nodeGallery = {
slideShow: require('node-gallery'),
mainGallery: require('node-gallery'),
}
and then access them as nodeGaller.slideShow({staticFiles....})
2. the better solution in my opinion would be to use the recommended way on the github page:
app.use('/gallery', require('node-gallery')({
staticFiles : 'resources/photos',
urlRoot : 'gallery',
title : 'Example Gallery'
}));
you're not setting node-gallery to any one variable, just initializing for that route.
Related
SAILS.JS
I have two forder in controller: admin and public.
I want to edit view.js file in config forder.
if controllers file in admin forder, it call a layout: layout-admin
if controllers file in public forder, it call a layout: layout-public
but i don't know do it.
please support for me with this. thank a lot!
You can do what you want, look the doc here : http://sailsjs.org/documentation/reference/configuration/sails-config-views
The layout attributs can only be a string or a boolean, there no way actually to define a layout with a function or for an entire controller.
You can make a feature request to sails to see this feature in a next version.
You can specify layout file in your controller like this :
myAction : function (req, res)
{
var layout = "layout-public";
if(req.session.authenticated)
{
layout = "layout-admin";
}
res.view("myview", {
layout : layout
});
}
I am creating an NodeJs + AngularJS Application. I have list of Hotels stored into database. I want to create dynamic route based on the hotel name and the load partial view based on property ID.
E.g In my database I have:
HotelID HotelName
1 example hotel
2 second example hotel
3 third example hotel
In app.js I want something like this
var hotelierApp = angular.module('hotelierApp', ['ngRoute', 'ngCookies', 'pascalprecht.translate', 'hotelierApp.services', 'hotelierApp.directives', 'hotelierApp.filters', 'hotelierApp.controller']);
hotelierApp.run(function ($rootScope) {
$rootScope.langId = 1;
})
hotelierApp.config(['$routeProvider', '$locationProvider', '$translateProvider',
function ($routeProvider, $locationProvider, $translateProvider) {
angular.forEach(hotels, function (hotel) {
$routeProvider.when(hotel.name.replace(" ","-"), { templateUrl: 'partials/property', controller: propertyCtrl });
});
angular.forEach(reviews, function (review) {
$routeProvider.when(review.title.replace(" ","-"), { templateUrl: 'partials/review', controller: reviewCtrl });
});
$locationProvider.html5Mode(true);
$translateProvider.useStaticFilesLoader({
prefix: 'data/locale-',
suffix: '.json'
});
$translateProvider.preferredLanguage('en');
$translateProvider.useLocalStorage();
}
]);
Here Hotels/reviews will be the list coming from database by making api calls and also I want to pass their corresponding Ids as route params to the controller.
I have many other section in my application for which i have to create routes from database.
Please help.
Regards,
- Manoj
There is no reason you need to do that.
i'm pretty sure your routes can be factored into something like
$routeProvider.when("/:id/:name", {
templateUrl: 'partials/property', controller: propertyCtrl })
then use $routeParams to get name of the hotel in your controller.As for template urls,your can pass a function instead of a string that will resolve the name of the template you need to use.
templateUrl:function(pathParms){...}
So no need to use angular.forEach.
While this is using another router: http://dotjem.github.io/angular-routing/ the same stuff is possible in tne core router.
Here is illustrated what #mpm is saying you can do: http://plnkr.co/edit/8XuJswpx0FucwMczWTHF?p=preview
In your case I think Option1 would be most appropriate, this is because you talk about a generated url pr. hotel, which makes me assume that there is a large similarity in layout for all hotels.
When that is the case, they may as well share template, where you can just populate the template with the hotel specific data.
How do I create a catch all route with the new Attribute routing in MVC
I tried this:
[Route("{pagenode}", Order = 999)]
But when I have a named route like
[Route("contact"]
I get the "Multiple controller types were found that match the URL. This can happen if attribute routes on multiple controllers match the requested URL." error.
This can be done with Attribute Routing if the first "directory" in the path is fixed.
For example, to match anything that hits /questions or /questions/4 or /questions/answers/42 then you would use [Route("questions/{*catchall}"].
You can't do this with Attribute routing, do this the MVC4 way:
Map a route in your routemapper like this:
routes.MapRoute("RouteName","{*url}",new { controller = "YourFancyController", action = "YourAction" });
This will be your catch-all Route.
If you would like to map all the routes to their controller you can do this:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
AreaRegistration.RegisterAllAreas();
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional });
}
The ability to do this must have changed.
In my default controller, still called 'Home' I have one result method which I want executed for an unrecognised URL structure. The routing attribute is: [Route("{*catchall}")]. This is successfully executed for any old thing.
I have a second method which is always successfully executed based on its route (and I've thrown a few route 'styles' at it to see if it always works). I can only assume that the framework always registers the catch-all route last as this is the behaviour I'm seeing.
This is also a brand new, not configured (except for nuGet packages) MVC 5 project excepting that my methods have been changed to return JsonResult (not even doing their job yet but returning little anonymously typed objects). The catch-all for example returns: Json(new { Message = "Invalid Request" }, JsonRequestBehavior.AllowGet). Yes, yes I set the StatusCode first etc etc, this isn't about MY project ;).
I'm sure I haven't left anything out since there's so little to it but if any clarification is wanted I'll see about adding it.
I am new to Node, and I'm using Mongoose as a driver for MongoDB. I'm using Jade for my views.
My "Edit" views and my "Show Object" views are looking great. However, I'm getting an "object is not defined" error when trying to create a new object.
I have this in my server.js:
require('./models/object');
app.resource('objects', require('./routes/objects'))
and in my routes folder I have:
exports.new = function(req, res) {
res.render('object/new')
}
finally my view looks like this:
h1 New Object
form(method='post', action='/objects')
.formRow
label Name:
input(type='text', name='object[name]', value=object.name)
.formRow
label Email:
textarea(name='object[email]')= object.email
.formRow
input(type='submit', value='Create')
Is there something I am leaving out? Thank you for your help.
It seems that you are using the express framework
you need to pass in the object while rendering the view.
res.render('object/new', { object: 'your object here'})
you may see http://expressjs.com/guide.html#view-rendering for example
I have been looking at the Todo list example (source) for Backbone.js. The code uses local storage, and I wanted to try and convert it so that it operated via a RESTful webservice.
Suppose the webservice already exists at the route todos/. I figured I need to add in a url piece into Backbone.Model.extend and remove the localStorage: new Store("todos") line when we perform Backbone.collection.extend.
window.Todo = Backbone.Model.extend({
url : function() {
return 'todos/'+this.id;
}
// Default attributes for a todo item.
defaults: function() {
return {
done: false,
order: Todos.nextOrder()
};
},
// Toggle the `done` state of this todo item.
toggle: function() {
this.save({done: !this.get("done")});
}
});
What is the proper way to do this?
Url should be set in Collection, if you have need for diferent urls than those created by collection than declare url in model.
You need to remove
<script src="../backbone-localstorage.js"></script>
from index.html since it is linked after backbone.js and effectively overrides Backbone's sync method to store in localStorage.
I would leave the model as it is in the Todos example. In the collection class add this property:
window.TodoList = Backbone.Collection.extend({
...
url: '/todos',
...
}
Calling fetch() on the collection should retrieve a list of Todo objects.
If you are using Rails you need to set ActiveRecord::Base.include_root_in_json = false otherwise Backbone.js will not be able to pull out the Todo objects from the returned json.