HandleInvalidRoute not working with Durandal - durandal

Here's my shell.js vm:
var vm = {
router: router,
auth: auth,
viewAttached: function () {
},
activate: function () {
router.useConvention();
router.handleInvalidRoute = function (route, params) {
debugger;
toastr.info('No Route Found: ' + route);
};
router.map([
{ url: 'error', moduleId: 'viewmodels/error', name: 'Error', visible: false }
]);
router.mapAuto();
if (auth.isAuthenticated)
//return router.activate('folder/2');
return router.activate('home');
else {
return router.activate('home');
}
}
};
return vm;
});
When I navigate to an invalid route (/folders, for example), the debugger in my handleInvalidRoute block isn't hit, and I get a scripterror from require.js:
GET http://appname.com/App/viewmodels/folders.js 404 (Not Found)
require.js:33 Uncaught Error: Script error
http://requirejs.org/docs/errors.html#scripterror require.js:8 J
require.js:8 j.onScriptError
That's all I have to work with. Any idea what's going on?

This has been answered by #EisenbergEffect in the Durandal newsgroup https://groups.google.com/forum/#!topic/durandaljs/eZrIcgn3aU8.
It is because you called mapAuto which always attempts to map urls to
modules, whether or not they actually exist. Effectively,
handleInvalidRoute will never be called.

Related

How to access object on Vue front end from axios proxy

I have a locally hosted mongodb database with mongoose, express, axios, and a Vue front end. Right now I'm trying to access a single object from an exported array, but I'm missing the mark and getting "undefined" as the result.
vue.config.js:
module.exports = {
devServer: {
proxy: 'http://localhost:3000',
}
}
here's the front end Vue script meant to use the objects:
import axios from 'axios';
export default {
name: 'Game',
data () {
return {
pages: [],
currentPage: {},
pageTitle: "",
pageText: "",
options: [],
}
},
created () {
this.getPages();
},
methods: {
async getPages() {
try {
let res = await axios.get('/api/pages');
this.pages = res.data;
console.log(this.pages);
this.currentPage = this.pages[0];
console.log(this.currentPage);
return true;
} catch (error) {
console.log(error);
}
},
my "get" endpoint in pages.js:
router.get('/', async (req, res) => {
try {
let pages = await Page.find();
res.send({pages: pages}); //send result of search for pages as list of pages called "pages"
} catch (error) {
console.log(error);
res.sendStatus(500); //500 = server could not fulfill request
}
});
the route in server.js:
const pages = require('./routes/pages');
app.use('/api/pages', pages);
app.listen(3000, () => console.log('Server listening on port 3000!'));
module.exports = app;
and here's the console output, with the "pages" object from vue's data property and the "currentPage" that's supposed to be at pages[0] (printed to console in earlier example):
I can access the api at 'localhost:3000/api/pages' just fine, but how do I break into that array and access the first page object? I want to get an object from the list axios fetches from mongoose, then hold that object in a variable so I can access it's properties. The whole "pages > [[Target]] > pages > [ ]" is part of the problem I'm sure, but I don't know what to tell the code to open it.
Whoops! I realized my mistake. In pages.js I should have sent "res.send(pages);" After a whole couple days too XD

Lodash ReferenceError: _ is not defined in Vue even though it works everywhere else

In my component shoppingCart.vue file I'm calling a simple method:
saveCart : _.debounce(() => {
console.log('hi');
}, 2000),
But I get the Error: Uncaught ReferenceError: _ is not defined.
Now gets the fun part. If I change the function for example to:
saveCart(){
console.log(_.random(0, 5));
}
Everything works perfekt and I get for example: 4. To make it even more interesting, I have some other components that are using _.debounce for example searching for Users:
findUsers: _.debounce(
function (term)
{
let vm = this;
axios.get('/search', { params: { user: term }})
.then(response => {
vm.updateResult(response.data);
});
}
,500),
And it works perfect.
So here are some background informations for you. I think I have a guess where the problem is but I'm not sure:
I'm using Laravel and I'm import Lodash through bootstrap.js with
window._ = require('lodash');
My component shoppingCart.vue is being called by Buying.vue.
Buying.vue is called by
export default new VueRouter({
mode: 'history',
routes: [
{
path: '/:user/:title',
component: require('./views/buying/Buying'),
},
],
});
Maybe the problem is somewhere because of vue router? But I tried to make a jsfiddle http://jsfiddle.net/gnu5gq3k/, but my example works in this case... In my real life project test2 creates the problem...
What could be the problem? What kind of informations do you need to understand my problem better?
Edit
I must be doing some easy mistake that I cannot see: I changed the code to:
debounce(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
},
saveCart: this.debounce(() => {
// All the taxing stuff you do
console.log('blubb');
}, 250),
And I cannot call my own function!
Uncaught TypeError: this.debounce is not a function
at Object
What am I doing wrong?
Error: Uncaught ReferenceError: _ is not defined.
In shoppingCart.vue do import _ from 'lodash';:
<script>
import _ from 'lodash';
export default {
// ...
}
</script>
Uncaught TypeError: this.debounce is not a function
at Object
You can't use this while constructing an object (the object is not created yet). You can use it in functions because that code is not executed right away.
window.a = "I'm window's a";
var myObj = {
a: 1,
b: this.a
};
console.log(myObj); // {a: 1, b: "I'm window's a"}
My solution is a workaround:
mounted(){
let that = this;
let savingCart = _.debounce(() => {
that.saveCart();
}, 1000);
window.events.$on('savingCart', savingCart);
}
This works fine

Vue: Unhandled promise rejection Error: Request failed with status code 404?

My API url is http://localhost:5000/api/user/list, data shows as:
[{"Id":1,"name":"Michael","pwd":"123456","age":0,"birth":"2018-01-05","addr":"''"},{"Id":2,"name":"Jack","pwd":"123512616","age":0,"birth":"2018-01-05","addr":"''"}]
User.vue
import axios from 'axios';
export default {
data() {
return {
filters: {
name: ''
},
loading: false,
users: [
]
}
},
methods: {
getUser: function () {
axios.get('http://localhost:5000/api/user/list', function (data) {
this.$set('users', data);
})
}
},
mounted() {
this.getUser();
}
});
The error is :
Unhandled promise rejection Error: Request failed with status code 404(…)
How can I fix it?
You should register a handler for your axios request.
Currently you are using settings argument as a handler.
axios.get('http://localhost:5000/api/user/list').then(function (response) {
// this is your handler.
})
Btw, make sure you are not requesting via CORS.
In my case there was a spelling mistake in URL string. It is fixed after that correction.

Routing in BackboneJs, involving Jquery Mobile and Asp.Net MVC4

I'm trying to use backbonejs as my router, routing does not seems to work for subpath nor splat. I'm using MVC 4 together with Jquery mobile for this project and hopes it does not cause conflict in the routing.
The result of testing are below:
http://localhost gives me "Routed to home" in console. (correct)
http://localhost/#contacts gives me "Routed to contacts list" in console. (correct)
http://localhost/#contacts?1 stills gives me "Routed to contacts list" in console. (wrong)
http://localhost/#contacts/view/1 redirects me to http://localhost/contacts/view/1 and gives me a 404 error since I do not have such page. (wrong)
I have tried using splats, and I got the exact same problem as my 4th example. Please guide me on what I might be doing wrong.
Here's my code sample.
app.js
define([
'jquery',
'backbone',
'router',
], function ($, Backbone, Router) {
var initialize = function () {
$(document).on("mobileinit",
// Set up the "mobileinit" handler before requiring jQuery Mobile's module
function () {
$.mobile.ajaxEnabled = false
$.mobile.hashListeningEnabled = false
$.mobile.linkBindingEnabled = false
$.mobile.pushStateEnabled = false
$('div[data-role="page"]').live('pagehide', function (event, ui) {
$(event.currentTarget).remove();
})
});
require(["jquerymobile"], function () {
// Instantiates a new Backbone.js Mobile Router
this.router = new Router();
});
};
return {
initialize: initialize
};
});
router.js
define([
'jquery',
'jquerymobile',
'underscore',
'backbone',
'../../scripts/backbone/views/home/HomeView',
'../../scripts/backbone/views/footer/FooterView',
], function ($, Mobile, _, Backbone, HomeView, FooterView) {
var AppRouter = Backbone.Router.extend({
initialize: function () {
var homeView = new HomeView();
homeView.render();
var footerView = new FooterView();
footerView.render();
Backbone.history.start({ pushState: false });
},
routes: {
'contacts': 'contactList',
'contacts?:id': 'contactsDetail',
'contacts/view/:id': 'contactsDetail',
//'*actions': 'home',
'': 'home'
},
// Home method
home: function () {
console.log("Routed to home");
},
contactList: function () {
console.log("Routed to contacts list");
},
contactsDetail: function (id) {
console.log("Routed to contacts detail");
}
});
return AppRouter;
});

"Route Not Found" in console window when Durandal is trying to load first page of app

I'm getting "Route not found" in the console window on trying to load an app converted from 1.2 to 2.0. Is there any way I can debug what route it's trying to find at the point of failure please? It would be handy if it said, "cannot find route:/viewmodels/wrongfolder/startup" or something!
Please be aware that ALL of this was working perfectly prior to upgrading from 1.2 to 2.0, so it's differences in the Durandal settings that I need to address. No files have been removed or lost or moved, so it's not that things have changed in the app outside of the new versions of scripts being updated by nuget.
main.js and config.js live in root of "app" folder. Shell.js is in app/viewmodels and shell.html is in app/views. All views/viewmodels are in the relevant folders below the main /app folder.
I have a "config.js" file with routes returned:
var routes = [{
route: 'home',
moduleId: 'home',
title: 'Home',
nav: true
}, {
route: 'labTool',
moduleId: 'labTool',
title: 'Lab Tool',
nav: true
}];
var startModule = 'labTool';
main.js:
//specify which plugins to install and their configuration
app.configurePlugins({
router: true,
dialog: true,
widget: false
});
app.start().then(function () {
viewLocator.useConvention();
router.makeRelative({ moduleId: 'viewmodels' });
app.setRoot('viewmodels/shell');
router.handleInvalidRoute = function (route, params) {
logger.logError('No route found', route, 'main', true);
};
});
Shell.js:
var inEditMode = ko.observable(false); //set edit mode to false at start
var shell = {
activate: activate,
router: router,
inEditMode: inEditMode
};
return shell;
function activate() {
return datacontext.primeData()
.then(boot)
.fail(failedInitialization);
}
function boot() {
logger.log('Application Loaded!', null, system.getModuleId(shell), true);
router.map(config.routes).buildNavigationModel();
return router.activate(config.startModule);
}
function failedInitialization(error) {
var msg = 'App initialization failed: ' + error.message;
logger.logError(msg, error, system.getModuleId(shell), true);
}
Some of the code may still need editing to handle the change from 1.2 to 2.0 but I think I have most of it now.
I had a similar problem after the upgrade and creating a default route with a route property of '' sorted it for me.
So instead of using your startModule property try setting you labTool route to have a route property of ''.
In case anyone else runs into this, this error can also occur if you have non-ascii characters in the route name.
Not working:
{ route: 'Møøse', ... }
Working:
{ route: 'Moose', title: 'Møøse', ... }