Vue Router and Vuex - laravel-5

I have 2 questions.
1. How can I catch undefined routes and redirect to 404 page?
2. How I can use Vuex actions to get data from api? I know that vuex mutations must be sync and actions async. But I can get data with mutations and can use then promise. but can't in actions or I do anything mistake. Please give me beautiful example for that(component type). I use vuex in laravel mix in Laravel project. Thanks...

Generally speaking, you shouldn't be getting undefined routes if you're defining all of the routes within an app. You can define a redirect in your routes configuration as such:
[
{
path: 'admin/posts/list',
name: 'post-list',
},
{
path: 'admin/posts',
redirect: 'admin/posts/list'
}
]
// you can also redirect to a named route instead
// of a path like this:
{
path: 'admin/posts',
redirect: { name: 'post-list' }
}
If you wanted to do a "catch all" that grabs any paths not matched and redirect to your 404 component/view, then you could do it like this:
{
path: '*',
redirect: '/404'
}
Make sure that is at the bottom of your routes definition as the last route because it will catch any routes in the tree it is above.
As for your question about mutations/actions, asynchronous API requests like fetching data from an API only every happen within actions when you're using Vuex.Taken from the documentation on actions:
actions: {
actionA ({ commit }) {
return new Promise((resolve, reject) => {
setTimeout(() => {
commit('someMutation')
resolve()
}, 1000)
})
}
}

Related

Laravel: Redirect the user to a custom 404 page when the given params are invalid

I made an application where a user can create some papers and see all data in a template. Every paper has a joincode which is generated at its creation.
I defined the join route in my web.php like this:
Route::get('/conceptPaper/lobby/{joincode}', 'App\Http\Controllers\ConceptPaperController#join');
and the join function in the controller the following way:
public function join($joincode)
{
try {
$conceptPaper = ConceptPaper::where('join_code', $joincode)->firstOrFail();
return response()->json($conceptPaper);
} catch(ModelNotFoundException $e)
{
return view('errors.404');
}
}
I used firstOrFail to check if the join code exists. If it exists it should return a response, otherwise it should redirect the user to a custom 404 page.
I created a custom component which gets the join code as a route param and shows the concept paper
{
path: '/conceptPaper/lobby/:joincode',
name: 'conceptPaper',
component: () => import('./views/ConceptPaper.vue')
},
So when the user joins a lobby with the right code he gets redirected to the page with all data from the corresponding paper:
showPaper: async function (conceptPaper) {
const joinCode = conceptPaper.join_code;
this.$router.push({ name: "conceptPaper", params: { joincode: joinCode }, });
},
My problem is that when the user types in the wrong code he still gets redirected to the view. When I check the response in the network tab its shows the 404 page.
I think I built it fundamentally wrong. Can anyone tell me how to do it the right way? When the suer types in the correct join code he should see the ConceptPaper.vue view. When the code is wrong he should be redirected to the 404 page.
From your code I'm assuming that you're using VueJs as an SPA and you're retrieving the data from your laravel backend API.
Based on that, your join function is supposed to return json data that you use in your frontend, but in case the ConceptPaper was not found, you return a view instead of json, which won't change much because you're just changing the data that your front-end receives, but the front-end component is not changed.
What I'd do is remove the try catch block, which will return a 404 response from the API, and handle the 404 case in vue, and create a NotFound view in vue.
Laravel
public function join($joincode)
{
$conceptPaper = ConceptPaper::where('join_code', $joincode)->firstOrFail();
return response()->json($conceptPaper);
}
Vue
router/index.js
const routes = [
// previous routes
{
path: '/not-found',
name: 'NotFound',
component: () => import('../views/NotFound.vue')
}
]
NotFound.vue
<template>
// page here
</template>
export {
name: 'NotFound'
}
And finally handle the not found API call, if you are using axios
axios.get('/conceptPaper/lobby/-1000')
.catch(function (error) {
if (error.response.status === 404) {
this.$router.push('NotFound');
}
});

nuxtjs middleware rest API raw data requests

I have build nuxtjs example with built in rest API requests with middleware technique. In index.js of my middleware section I put some code :
export default {
handler(req, res) {
res.write('Everything ok!')
console.log(req);
console.log(res);
res.end()
},
path: '/test15'
}
When I call http://ip:port/test15/?cmd=somecmd&param=testparam
In console.log I get params data in log, everything nice. No matter which method used, post or get, it also fixed in log.
The problem is when I try to send raw data (ex json) in request body or form data. I can`t see them in any log output.
So question is, is it possible to send some data in such requests via middleware ?
Thanks!
middleware in nuxt is a sandwich for internal routes aka client side. For your question serverMiddleware is the answer that work on the server side. You can checkout more here
Quick example:
In your nuxt.config.js file add like below
serverMiddleware: [
{ path: '/api/subscribe', handler: '~/api/subscribe' }
],
Then create an api folder you can create subscribe.js file to add relative api route.
import express from 'express'
const app = express()
app.get('/subscribe', async (req, res) => {
res.send('love to the world');
})
export default {
path: '/api',
handler: app
}

Nuxt.js router.push doesn't fully redirect to another page while using asyncData query

I am using asyncData query in one of my pages:
async asyncData({$axios, query}) {
const id = query.id;
try {
const {data} = await $axios.$get(`http://localhost:8000/api/question/${id}`);
return {
question: data
}
} catch (e) {
console.log(e);
}
},
Whenever I try to access another route from this page, for example:
#click="$router.push('/solution'); addTodo(question.keywords); addTodo(option.keywords)">
It redirects me to this page /solution, but the request to access API still goes from previous page (question/id)
Accessing localhost:3000/solution page:
CORS works in every other page, so I think the issue is here with redirections.
What would be possible solutions to fix this?
Also, this is what I see in Network tab:
I think referer should be: localhost:3000/solution
Adding 'paths' => ['api/*'] to Laravel back-end CORS config helped.

Axios Get request return html not data SPA

need some help. I'm trying to fetch data from my db using axios. My backend is Laravel. I have a 200 status http request but it returns the whole html not the data I'm expecting.
Here is my code for route
Route::get('/home', 'PostController#ajaxCall');
Route::post('/home', 'PostController#store');
Route::get('/{any?}', function () {
return view('welcome');
});
Here is my code for Home.vue for Axios request
export default {
components: {addForm},
data () {
return{
posts:[]
}
},
created() {
axios.get('/home').then(response => this.posts = response.data);
}
}
For my controller
public function ajaxCall(){
return response(Post::all());
}
It looks like you get to the ajaxCall() method by using the route '/home', but with axios, you are hitting "/" which returns a view called Welcome. Maybe you need to change the path you use in axios to '/home'?
It might be late but maybe someone else is looking for the solution
I was also facing this in SPA using laravel and VUE.
Route::get('/{any}', 'SinglePageController#index')->where('any', '.*');
SPA has this route, so whenever you write any other get route your app will redirect you to the home page, to avoid this either move this route at the end of your web.php
or write your other routes in api.php file.
In my case i solved it by changing the GET method to POST method.
Try that. It might help

MVC6 routing to single-page application without losing 404

I'm writing a single-page application with angular2 and MVC5. I'm new to both, though, and I'm having trouble with the routing.
I'd like to match URLs as:
/ -> go to my index page, which bootstraps angular
/api/{controller}/{id?} -> REST API
/{*anythingelse} -> if a file exists there, return it as static content; otherwise if angular can route it, have angular route it; otherwise return 404.
The second point's easy enough, and I can get the client-side routing working if I'm willing to give up 404 returns, but I can't seem to reconcile it all.
It seems like this ought to work:
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "api",
template: "api/{controller}/{id?}");
routes.MapRoute(
name: "spa",
template: "{*anythingelse}",
defaults: new { controller = "Home", action = "Index" });
});
and:
#RouteConfig([
{ path: "/", name: 'Splash', component: SplashView },
{ path: '/accounts/login', name: 'Login', component: LoginView },
{ path: '/accounts/register', name: 'Registration', component: RegistrationView },
{ path: '/home/...', name: 'Home', component: HomeView },
])
But that just serves Index.cshtml for every request that isn't a static file.
I feel like this must already be a solved problem, but I haven't been able to find anything online about it. How does one do this properly?
I'm using "HTML5"-style paths rather than hash-style.
So there are two ways to go about doing it. If you are using the HashLocationStrategy I would strongly encourage you to do this on your server side implementation as I have found it much easier to deal with.
Otherwise you could make your own RouterOutlet component that handled the exceptions. I am not 100% clear on how you could get it to work with your RouterConfig as I have not delved that deep into the routing aspect, but I bet you could see if there exists a route then go there otherwise 404 error. Here is my code that deals with seeing if a user is logged in with Json Web tokens.
import {Directive, Attribute, ElementRef, DynamicComponentLoader} from 'angular2/core';
import {Router, RouterOutlet, ComponentInstruction} from 'angular2/router';
#Directive({
selector: 'router-outlet'
})
export class LoggedInRouterOutlet extends RouterOutlet {
publicRoutes: any;
private parentRouter: Router;
constructor(_elementRef: ElementRef, _loader: DynamicComponentLoader,
_parentRouter: Router, #Attribute('name') nameAttr: string) {
super(_elementRef, _loader, _parentRouter, nameAttr);
this.parentRouter = _parentRouter;
}
activate(instruction: ComponentInstruction) {
if (!localStorage.getItem('jwt') || !tokenNotExpired('jwt')) {//Public Routes does not work with Hash Location Strategy, need to come up with something else.
// todo: redirect to Login, may be there is a better way?
if(localStorage.getItem('jwt')){
localStorage.removeItem('jwt');
}
this.parentRouter.navigate(['Login']);
}
return super.activate(instruction);
}
}
As you can see I handle my checking for the Token, and if they don't have a token they can only go to my login page. Then in your app.component or your bootstrapped component just use this as your router-outlet instead of the original.
Sorry I can't be more helpful but I hope this gets you pointed in the right direction!
I think you're looking for a regex route constraint:
routes.MapRoute("app", "{*anything}",
new { controller = "Home", action = "Index" },
new {anything = new RegexRouteConstraint("^(?!api\\/).+") });
This will prevent your catch all route from mapping to any request that begins with "api/"

Resources