sammy.js url not found cause of subdirectory - javascript

Hi I create a spa with knockout, amplify and sammy.
If I now click an a link like:
#/page?s=About
it links to url.de/subdirectory/#/page?s=About which is right but the console fires following error:
GET url.de/About 404 (Not Found)
because it should be:
url.de/subdirectory/About
My sammy code is:
var app=$.sammy(function () {
// define prexecutes
// update parameters in appModel from request for all routes
this.before('', function() {
//setParameters(this);
});
// authenticate on any page except for login and logout routes
this.before({except: {path:/\/(login|logout|hp)/}}, function() {
});
// actual routes
// home
this.get('#/', function() {
appModel.page("home");
return false;
});
// content
this.get('#/page', function(eventContext) {
content(eventContext);
});
});
app.run('#/');
How do I get sammy not ignoring my subdirectory in which my site is?

You can try with another custom route definition like this
this.get('#/page/:s', function(eventContext) { // where s is parametre
content(eventContext);
});
also use url like this
#/page/About // it will read 'About' as value of parameter 's'
instead of
#/page?s=About
Hope this helps

I ran into a similar situation myself recently. I could not find any configuration options or workarounds that would allow Sammy.js to route to a subdirectory. My solution was to create a virtual host on the server hosting my app with the subdirectory as the subdomain in order to place the app at the document root. In your case, the virtual server would map from url.de/subdir/About to subdir.url.de/About. I realize that this may not be possible for you (since I don't know how much control you have over your hosting environment), but it got me moving again pretty quickly. Hope this helps.
P.S. As a small aside, I just browsed through the Sammy.js source at https://github.com/quirkey/sammy, and it appears that the subdirectory is stripped out (in error) to fix an IE quirk. https://github.com/quirkey/sammy/blob/master/lib/sammy.js#L301 may be the problem.

Related

cypress goes in an infinite loop to lauch webpage

I am trying to access a URL outside of the defined environment but the page load goes in a loop and does not load the home page once the authentication is completed from Login screen
My implementation is as below:
The below utility.js file launches URL based on the environment the user selects:
export class Utility {
getBaseUrl(){
let envs = Cypress.env('ENV');
console.log(envs)
if(envs == 'production'){
return "https://prodsite.site.com.au";
}else if(envs =='canarys'){
return "https://stagenv2.site.com.au";
}else if(envs =='stage'){
return "https://stageenv.site.com.au";
}
}
}
snippet of Cypress.json file configured as below:
{
"env": {
"nzUrl": "https://search.infotrack.nz"
},
"viewportWidht": 980,
"viewportHeight": 1200,
"baseUrl": "https://stageenv.site.com.au",
}
To call the utility.js, have passed the url in a constant
const url = new Utility().getBaseUrl();
Ideally, to launch the url, i use
cy.visit(url)
To access the environment variable,
cy.visit(Cypress.env('nzUrl'));
After launching the application. The login screen loads up , authenticates itself , but to show up the home page, the page goes in a loop and fails to load it self
The baseurl works as expected , no issues there.
Facing this issue when accessing the the url in env variable
Looking for some help here. I have tried the following:
The website launches perfectly manually
Configured cypress.json with a url for launching a webpage other than baseurl, this approach did not work
Troubleshooted the webelements
I am looking forward for any help / suggestions with this information. Appreciate your kind help in advance
Basically cypress uses baseURL configuration to navigate by the commands cy.visit() and cy.requests() as you can see in the documentation here
I really recommend you to create a config file for each environment like
production.json
canarys.json
stage.json
Using that you can open your page just using cy.visit('/') or a page like cy.visit('/main') and cypress will make all the hard job for you. You don't need an extra class to get baseURL.
It may help you: https://www.cypress.io/blog/2020/06/18/extending-the-cypress-config-file/

Render PDF in Forge Viewer with PDF Extension - pdf.worker.js throws warning

While trying to render a PDF, which gets served through our own API, the pdf.worker.js throws the following warning and the rendered PDF always keeps being completely white.
And I only see this (it's a wide PDF, but gets correctly rendered within the Demo):
Our Client application is served with angular, however I could not totally encapsulate the problem. With a simple and new angular application I was able to render a PDF File, served from our API but in my bigger client application the error above keeps occurring and I don't know why.
I'm using this Code to load the PDF, which inspired by this GitHub and this Blog Entry from Autodesk.
Autodesk.Viewing.Initializer({ env: 'Development', useADP: false }, () => {
const viewer = new Autodesk.Viewing.GuiViewer3D(
document.getElementById('forgeViewer'),
);
viewer.start();
const url =
'http://api.pdfFileToRender.pdf';
viewer.loadExtension('Autodesk.PDF').then(() => {
viewer.loadModel(
url,
{},
model => {
console.error('Success: ', model);
},
(errorCode, errorMessage, errorArgs) => {
console.error('Error Code: ', errorCode);
console.error('Error Msg: ', errorMessage);
console.error('Error Args: ', errorArgs);
},
);
viewer.loadExtension('Autodesk.Viewing.MarkupsCore');
viewer.loadExtension('Autodesk.Viewing.MarkupsGui');
});
});
The loadModel Function also calls the onSuccessCallback and I see "Success" in my Console.
For me it is not possible to integrate the PDF Extension into my Client App. Does anyone know a solution or have a hint for this, I gladly appreciate it.
It is also important for me, that the PDFs are rendered locally and are not uploaded to any Forge API.
For serving the Client Application I'm using Angular 11.2.7 and Typescript 4.1.5. I'm loading the ForgeViewer with the Version 7.36.0 but the Problem occurs also with other Versions.
For anyone interested, I could figure it out. Our own application was defining array prototype functions. However this is a problem for pdf.js which get's used by the PDF Extension from Forge.
The root problem was by defining array prototype functions like this:
Array.prototype.myFunction = function(...) {...}
We had to either exclude our own array functions or write it that way:
Object.defineProperty(Array.prototype, 'myFunction', {value: function(...) {...})
So, if you application defines array prototype function, use Object.defineProperty or don't use them at all. This seems to solve the Issue. Cheers.

MEAN.js - How to redirect after Push function

Im new to MEAN.js and im trying to figure out how to redirect a user after posting a comment to an article.
The function called is addComment and adds the comment fine after pressing submit. What i need to know is how to redirect similar to the way it redirects after posting an article.
addComment() Pushing to a nested Array
$scope.addComment = function () {
var article = $scope.article;
$scope.article.comment.push({details: this.details, created: Date.now(), user: user._id});
$scope.update(false);
this.details = '';
console.log(article._id);
$location.path('articles/' + article._id);
console.log(article._id);
};
I need to use the $location.path('articles/' + article._id); properly if the push was successful.
Thanks in advance.
Try injecting $window and run a lower level location api with $window.location.href = 'path';
also it may matter that you want to keep your data in sync so try $location.path('/someNewPath').replace();
also take a look at your $locationProvider service settings
$location service configuration To configure the $location service,
retrieve the $locationProvider and set the parameters as follows:
html5Mode(mode): {boolean|Object} true or enabled:true - see HTML5
mode false or enabled:false - see Hashbang mode requireBase:true - see
Relative links default: enabled:false
hashPrefix(prefix): {string} prefix used for Hashbang URLs (used in
Hashbang mode or in legacy browser in Html5 mode) default: ""
More information about the $location service in the Angular docs
https://docs.angularjs.org/guide/$location

How to handle file download errors with angularjs?

Downloading files looks very trivial and there are many working solutions. Working until the server says 401 UNAUTHORIZED. My requirements are rather natural:
In no case the current window may be replaced.
I don't want to open a new window, as it makes no sense.
In case of an error, some message must be shown to the user.
I tried to use an iframe as a target of the link and hoped to be notified in case of an error. I see I was naive.
I could imagine to place some script in the iframe which would notify main page onunload. It look a bit complicated so I'm asking first instead.
I could ask the server about the outcome. This would surely work, somehow. But it's complicated too, as there's timing problem and the session is expired, so I'd have to circumvent this.
You can use a Blob object to trigger file download from javascript. This is introduced with the File API and still in Working Draft state. So you'll have limited browser-support. As of 2015, you have wide browser support for Blob URLs and Blob Constructor.
<div ng-controller="appController" ng-app="app">
<a ng-href="{{ fileUrl }}" download="file.txt">download</a>
</div>
var app = angular.module('app', []);
// Angular prepends "unsafe" tag in ng-href to prevent XSS
// so we need to sanitize this
app.config(['$compileProvider', function ($compileProvider) {
// for Angular 1.0.x and 1.1.x, you should use urlSanitizationWhitelist
$compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|blob|ftp):/);
}]);
app.controller('appController', function ($scope, $window) {
// Creating a Blob with our data for download
// this will parse the URL in ng-href such as: blob:http...
var data = 'some data here...',
blob = new Blob([data], { type: 'text/plain' }),
url = $window.URL || $window.webkitURL;
$scope.fileUrl = url.createObjectURL(blob);
});
See a demo fiddle here.
There are some libraries to extend browser support for this such as Blob.js
You should also check out FileSaver.js which also falls back to data:URI.
You could handle HTTP errors without it interrupting your controller / service logic by making use of HTTP interceptors. When an error happens, handle it in an interceptor and then broadcast the error to an error handler, which could display an error to the user.
$httpProvider.interceptors.push(function($q, dependency1, dependency2) {
return {
'request': function(config) {
// same as above
},
'response': function(response) {
// same as above
}
};
});

Crossroadsjs routing: how to use it?

I am facing the same problem as this one as I am trying to figure out how to use crossroads for a few hours now and nothing seems to work. its webiste is just another poor documented site... I think I am probably daft! I wonder if anyone has made it?
html head,
<title>Crossroads</title>
<script src="js/libs/signals.js"></script>
<script src="js/libs/crossroads.min.js"></script>
<script src="js/app.js"></script>
</head>
app.js, just as simple as this,
crossroads.addRoute('/news/{id}', function(id){
alert(id);
});
so I try it out on my localhost browser,
http://localhost/crossroadjs/#/news/123
nothing happens. I thought it would be 123??
Crossroads doesn't handle history/state change events from the browser. From their site:
A routes system shouldn't do anything else besides routing.
Instead, the site recommends Hasher for this purpose and gives a rather complete looking example:
//setup crossroads
crossroads.addRoute('foo');
crossroads.addRoute('lorem/ipsum');
crossroads.routed.add(console.log, console); //log all routes
//setup hasher
function parseHash(newHash, oldHash){
crossroads.parse(newHash);
}
hasher.initialized.add(parseHash); //parse initial hash
hasher.changed.add(parseHash); //parse hash changes
hasher.init(); //start listening for history change
//update URL fragment generating new history record
hasher.setHash('lorem/ipsum');
Alternatively you could use a different history plugin, or write something yourself. But crossroads leaves that part up to you.
Crossroads.js gives crossroads.addRoute(pattern, [handler], [priority]); API to add route patterns. However, when the first time you load the page Crossroads does not automatically initiate the parser to check against the url of the page. You need to add crossroads.parse(document.location.pathname); on you document load to trigger the route. Check out Crossroads.js Tutorial.

Categories

Resources