What's the different between browserHistory.push() and location.replace() - location

I build my project with react, when I want to change the URL I find both browserHistory.push(myUrl) and location.replace() are worked. So I want to know what's the different between them.
divClick() {
location.replace('/doctor/task');
// browserHistory.push('/doctor/task');
}
render() {
return (
<div>
<div onClick={this.divClick.bind(this)}>Change</div>
</div>
);
}

History Push
The user can go forward and backward in the browser and the url will change. It works like a programmatic link with no affect on current url.
Location Replace
The link of the page is set to the new one, but the user can't go between the replaced.
Hope this will help you ;)

Related

Change 404 page in vuepress

Is it possible to change / customize the 404 page of Vuepress without ejecting and having to change the whole theme?
I am currently using the enhanceApp.js, but I'm unsure how I can change the router options (the catchall route) as the Router is already created. The way I got it working right now is this:
router.beforeEach((to, from, next) => {
if (to.matched.length > 0 && to.matched[0].path === "*") {
next("/404.html");
} else {
next();
}
});
However, this feels like a hack as I always redirect to a custom and existing page containing my 404. Is there a more official way to do this?
I have a site based on Vuepress 1.5.x, and I was able to simply create a page named NotFound.vue under theme/layouts. No enhanceApp.js changes needed.
Vuepress itself seems already aware of this reserved layout name, based on the code here.
I previously had that page named 404.vue, but I was getting a warning saying that pages should follow proper HTML 5 component naming standards. Simply renaming it to NotFound.vue did the trick.
Contents of my NotFound.vue file:
<template>
<BaseLayout>
<template #content>
<v-container class="text-center">
<div class="py-6" />
<h1>Oops!</h1>
<p>Nothing to see here.</p>
<v-btn class="cyan--text text--darken-3"
exact :to="'/'" text>Go home</v-btn>
</v-container>
</template>
</BaseLayout>
</template>
<script>
export default {
name: "NotFound"
};
</script>

check in blade view if image is loaded or 404

Is there a way to check in a blade view if an image is really there or not?
I need to show results from a search box.
The results are many boxes with infos and a picture for each box.
The point is in my DB I store links to images that are on remote servers and also name of images that are stored locally.
So what I am doing is check if the file exists locally and if so use it and if not look on the remote server (if the picture data is not NULL it's either there or in a remote server).
I was trying to check if file exists using curl and it works but for big collections it takes too much time to finally spit the data to the view (every link has to be checked).
So what I want to do, if possible, is check directly in the blade view if the picture is not broken (404) and if so replace with an "image-not-found.png" I store locally. How can I do that?
I usually handle this with JavaScript using the img tag's onerror event. Typically I add a few more bells and whistles to the solution but this is it in a nutshell.
Plan JavaScript
function loadNextImage(id,uri){
document.getElementById(id).src = uri;
}
Plain HTML
<img src="http://local/image.jpg"
onerror="loadNextImage('image1', 'http://remote/imae.jpg'));"
id='image1' />
VueJS and Webpack
<template>
<img :src="local_url" #error="imgOnError()" ref="image"/>
</template>
<script>
export default{
name: 'Thumbnail',
props: {
local_url: String,
remote_url: String
},
methods: {
imgOnError: function (e) {
this.$refs.image.src = this.remote_url
}
}
}
</script>
You can use the func "file_get_contents" inside a try-catch block. I know i not the best way, but i could work for you.
Tray this (no the best way):
<?php
try{
$img = 'myproject.dev/image.jpg';
$test_img = file_get_contents($img);
echo "<img src='{$img}'>";
}catch(Exception $e){
echo "<img src='img/no-img.jpg'>";
}
?>

Redirect from method in Vue.js with Vue-router older than version 1.x.x

I'm not much of a frontend developer but I know enough javascript to do the minimum.
I'm trying to plug into a last piece of login however my vue components are:
"vue-resource": "^0.9.3",
"vue-router": "^0.7.13"
I'm not experienced enough to move up to v1 or v2 respectively.
I would like to achieve something similar to this.
However I'm not getting a successful redirect.
my app.js file:
var router = new VueRouter();
...
import Auth from './services/auth.js';
router.beforeEach(transition => {
if(transition.to.auth &&!Auth.authenticated)
{
transition.redirect('/login');
}
else
{
transition.next();
}
});
```
In my login.js file
```
methods: {
/**
* Login the user
*/
login(e) {
e.preventDefault();
this.form.startProcessing();
var vm = this;
this.$http.post('/api/authenticate',
{ email : this.form.email,
password : this.form.password
})
.then(function(response){
vm.form.finishProcessing();
localStorage.setItem('token', response.data.token);
vm.$dispatch('authenticateUser');
},
function(response) {
if(response.status == 401)
{
let error = {'password': ['Email/Password do not match']};
vm.form.setErrors(error);
}else{
vm.form.setErrors(response.data);
}
});
}
}
I tried to do as suggested:
vm.form.finishProcessing();
localStorage.setItem('token', response.data.token);
vm.$dispatch('authenticateUser');
vm.$route.router.go('/dashboard');
However all it did was append the url on top.
I see that the 3 previous events were successfully done but not the redirect.
it went from:
http://dev.homestead.app:8000/login#!/
to
http://dev.homestead.app:8000/login#!/dashboard
when I need the entire page to go to:
http://dev.homestead.app:8000/login/dashboard#1/
I think i have a missing concept in order to do the redirect correctly.
UPDATE
As per suggested i have added param: append => false but nothing happens.
what i did afterward was within app.js create a method called redirectLogin() with console.log() outputs - that worked. what i did further is i put vm.$route.router.go inside there and called the method via vm.$dispatch('redirectLogin'); and that also didn't work.
NOTE:
The HTML is being rendered in Laravel first. the route I originally had (and working) as login/dashboard and that route is available via normal Laravel route. the blade is being rendered via view template.
So far I've been trying to vue redirect over to login/dashboard (not working) perhaps I should somehow remove login/dashboard and use the route.map and assign login/dashboard?
I would rather keep the login/dashboard as a laravel route due to authentication and other manipulation.
For Vue 2
this.$router.push('/path')
As par the documentation, router.go appends the path in the current route, however in your case it is appending along with # in the router as well.
You can use param: append, to directly arrive at your desired destination, like following:
vm.$route.router.go({name: '/login/dashboard#1/', params: {append: false}})
Edited
If it is not happening, you can try $window.location method like following:
var url = "http://" + $window.location.host + "login/dashboard";
console..log(url);
$window.location.href = url;
I think their is a misunderstanding here of how vue-router works. It seems you are not wanting to load a new route with a corresponding component, rather you simply want to redirect to a new page then let that page load and in turn fire up a fresh instance of vue.
If the above is correct you don't need vue-router at all. Simply add the below when you need to load the page:
window.location.href = '/login/dashboard'
If you'd rather simulate a redirect to that page (no back button history) then:
window.location.replace('/login/dashboard')
EDIT
The above would be fired when you have finished all processing that the page must run to set the users state which the next page requires. This way the next page can grab it and should be able to tell the correct state of the user (logged in).
Therefore you'll want to fire the redirect when the Promise has resolved:
.then(function(response){
vm.form.finishProcessing()
// store the Auth token
localStorage.setItem('token', response.data.token)
// not sure whether this is required as this page, and in turn this instance of vue, is about to be redirected
vm.$dispatch('authenticateUser')
// redirect the user to their dashboard where I assume you'd run this.$dispatch('authenticateUser') again to get their state
window.location.replace('/login/dashboard')

Sammy intercepts a POST that is not one of the added routes

I have an application that uses Sammy for some simple client-side routing.
One of the pages has a "Download Pdf" button, which needs to do a POST to get and download a pdf document (not very resty, I know, but it has to be a POST due to the large amount of data I'm submitting). It does this using the old trick of dynamically creating, populating, and submitting a <form> element.
Everything works fine, except for I can see in the console an error from sammy that my route was not found. Note that this is not a route, or even a verb that Sammy should be handling.
Here is my reduced test case
Sammy(function initializeClientRouting(app) {
app.get('#/', show('#default'));
app.get('#/test', show('#test'));
function show(selector) { return function() {
$('section').slideUp();
$(selector).slideDown();
}; }
}).run('#/');
$('button').click(function() {
var form = $("<form method=post action: 'http://www.google.com'>").hide();
$('<textarea name=q>').text("search text").appendTo(form);
form.appendTo('body').submit().remove();
});
Does anyone know how to prevent this error? Is this a bug in Sammy?
It's a combination of sammy & JQuery behaviour (bug?). When generated dynamically the way you put it, the form tag is being rendered as
<form www.google.com'="" 'http:="" action:="" method="post">
This will try to POST to the current page which probably is something like
http://blah/# or http://blah/#/test
For some reason, Sammy will be triggered because of the hashtag, not finding a POST configured and log an error.
Fiddling with your example, what worked for me was:
var form = $("<form>");
form.attr('method', 'post');
form.attr('action', 'http://www.google.com');
$('<textarea name=q>').text("search text").appendTo(form);
form.appendTo('body').submit().remove();
This seemed to generate the proper HTML and remove the Sammy error.

Meteor users and backbone very slow

I created a project for easy content sharing. You can look at my project here:
SharingProject
You can use user#example.com with 123456 as password to test the site as verified user. Of course the site has some bugs yet...
I used the meteor user package and the backbone package to navigate through the pages.
On localhost, there is no problem. For testing I uploaded the project to the meteor server. Now while I am logged in and navigating through the pages, every time I navigate to a new page the app 'checks' the user on client side because of the url change. This is annoying...
Of course I could navigate through the pages only calling Session.set('page_id', ..) but my goal is to be able to send people an url to a specific page on the server.
The code is similar to the one in the todos example from the meteor page:
Meteor.subscribe('pages', function () {
if (!Session.get('page_id')) {
var page = Pages.findOne({}, {sort: {owner: -1}});
if (page)
Router.setPage(page._id);
}
});
...
var PagesRouter = Backbone.Router.extend({
routes: {
":page_id": "main"
},
main: function (page_id) {
Session.set("page_id", page_id);
},
setPage: function (page_id) {
this.navigate(page_id, true);
}
});
Router = new PagesRouter;
Meteor.startup(function () {
Backbone.history.start({pushState: true});
});
Why I am asking here: I searched the web and can't find anyone with the same problem. So either nobody tried this before or there is a simple solution for this?
Edit: How I call the pages
<template name="pages">
{{#each pages}}
<p>{{title}}
{{#if isauthor}}
<a class="delPage" href="javascript:delPage('{{_id}}')">delete</a>
{{/if}}
</p>
{{/each}}
</template>
I don't know how you are rendering the page links but a link like this :
http://pagesharingproject.meteor.com/a1fbacba-0ddf-4077-a653-294b428bbfb8
should read like:
http://pagesharingproject.meteor.com/#a1fbacba-0ddf-4077-a653-294b428bbfb8
Ok I solved the problem, changing (true)
Meteor.startup(function () {
Backbone.history.start({pushState: true});
});
to (false)
Meteor.startup(function () {
Backbone.history.start({pushState: false});
});
and of course adding an anchor like Mubix suggested. Thanks for the hint!
It is up to date on the site mentioned above.
I spend some time today on the backbone documentation, but I can't imagine why this is working? Especially I am wondering why
{hashChange: false}
doesn't work here?

Resources