[Vue Router warn]: No match found for location with path "/errManager/errMessage" - vue-router

I added the routes dynamically at the `router.beforeEach`,I can visit all pages. but when i refresh page at Dynamic Route page,i get a warning `No match found for location with path "XXXXX"` but use `router.getRoutes()`can get all routes.
this is my code
await store.dispatch(`user/${UserActionEnum.GET_USER_INFO}`)
const roles = store.state.user.roles
await store.dispatch(`permission/${PermissionActionsEnum.GET_PERMISSION_ROUTES}`, roles)
store.state.permission.permissionRoutes.forEach((item) => {
router.addRoute(item as RouteRecordRaw)
})
console.log(router.getRoutes()) //can get all routes
next({...to, replace: true})
i don't known how to fix it,i hope to get your help

Related

How to set and change default(root) router with vue-router(Vue 3 Composition API)

I asked this at two other places but couldn't get a good answer. I would be grateful if anyone here could help me with this. I also think this may help other in the future.
My problem is a bit specific.
I am trying to set the "/" router to for example "/team-12" .
"team-12" is selected by user and stored in localStorage or store(Pinia).
So for example if the user selected a team, the default router will be /team-12/ (".com/team-12/settings" etc.). All the website routing will be added after "team-12/" If not selected it will be team-1 or something like that. And the user can change the team, thus the default route will change and page will refresh.
I managed to set the route to localStorage value but I get an error:
[Vue Router warn]: No match found for location with path "/team-12"
Also I can't add other routes to "/team-12". How can I achieve this? If there is a better aproach, ignore the code.
I tried this: router.ts
router.ts:
const contractId = localStorage.getItem("contractId");
{
path: "/",
name: "home",
redirect: `/${contractId}`,
component: Home,
},
Component:
const selectTeamId = (teamId: string) => {
localStorage.setItem("teamId", organization);
console.log(localStorage.getItem("teamId"));
router.push({ name: "home" });
};

VueRouter make HTTP request within beforeEach

I am attempting to make an AXIOS request within router.beforeEach. However, it looks like the request is being made with my next destination URL being prepended; if trying to access /client/create, the beforeEach appears to prepend '/client/create' to the request.
Instead of '/api/participant/test/{some_id}' the request is being sent to '/client/create/api/participant/{some_id}'.
I'm not quite sure why this is happening. The documentation indicates that you could use a getPost() method to make requests:
beforeRouteEnter (to, from, next) {
getPost(to.params.id, (err, post) => {
next(vm => vm.setData(err, post))
})
},
However it seems the getPost() method is unrecognized, which could be because of the beforeEach call (the documentation does not show that this could be used with this particular method).
Here is the code with the AXIOS request.
router.beforeEach((to, from, next) => {
console.log(to.params.id);
// Check to see if the cookie exists
if (document.cookie.match(/^(.*;)?\s*participant_token\s*=\s*[^;]+(.*)?$/)) {
axios.get('api/participant/test/' + to.params.id)
.then(function (response) {
console.log(response.data);
})
.catch(function (error) {
console.log(error);
});
}
Any ideas on how this can be avoided? I imagine one could use beforeRouteEnter for each of the routes I have set up, but this would be a more elegant solution.
It should be
axios.get('/api/participant/test/' + to.params.id)
(with forward slash character at the beginner).
The more properly way to set baseURL in axios config
For example:
axios.defaults.baseURL = 'your base url';
First, there is no built-in getPost method in Vue.js. Documentation has mentioned it just as an illustration purpose.
Also, use root relative URL instead of relative URL that you are trying to use.
axios.get('/api/participant/test/' + to.params.id)
You are trying to use relative URL which is causing a problem for you. The more generic way would be to set default base URL in Axios global config.

How to grant access to only the routes defined?

I have the following code defined in Startup.cs:
services.AddMvc().AddRazorPagesOptions(options =>
{
options.Conventions.AddPageRoute("/ListVehicles", "/vehicle-list");
});
How do I only allow access to the page by using the url "vehicle-list" instead of just typing the cshtml file name ListVehicles in the url? I tried options.Conventions.Clear() but that didn't work.
You could achieve this with custom IPageRouteModelConvention that clears Selectors list in required PageRouteModel:
services.AddMvc().AddRazorPagesOptions(options =>
{
options.Conventions.AddPageRouteModelConvention("/ListVehicles", model =>
{
model.Selectors.Clear();
});
options.Conventions.AddPageRoute("/ListVehicles", "vehicle-list");
});
Now request to http://localhost/ListVehicles will result to 404 error, while request to http://localhost/vehicle-list will return ListVehicles.cshtml page.

How to get http refere in vuejs?

I would like to get from which page a user came from in my page.
Currently, I would like to get this info in my created() or mounted() pages. Using this.$router or this.$route but none of them contain this info.
I know in the navigation guards, we can use this :
router.beforeEach((to, from, next) => { })
to know where the page is comming from, but I don't want to use router.beforeEach because that is in found inside my main.js but where I want to get the referer is in my components page, either in created/mounted methods
Is this possible?
You can use this.$route.query in mounted() hook in App.vue. You don't need router.beforeEach, because it dosn't make sense. App.vue mounted one time, when app is loaded, so this a good place to check router query params.
router.beforeEach((to, from, next) => {
console.log(to.query)
console.log(to.query.utm_source)
})
if url product/3?utm_source=2.
Console logs
{utm_source: "2"}
2

res.render for routes on page reload?

(Using MEAN with UI Router)
The following code sends a json response for the route defined. This works fine when the template is rendered with UI Router; however, if I reload the page, because the response only contains json, I am left with an empty page rendering no html, only the json response.
router.get('/posts/:post', function(req, res, next) {
req.post.populate('comments', function(err, post) {
if (err) { return next(err); }
res.json(post);
});
});
Assuming this is a standard issue, how can I best allow this page to res.render('index') when the page is reloaded and respond with the json response? Should I,
Create a separate route for the json response which is called as a post promise with UI Router
Have the /posts/:post route simply respond with res.render('index')?
Thank you for any responses, not sure what the usual practise is for such issues!
It took me a while to find a working solution to this due to many of the examples online having different directory structures. I placed a catch all at the end of my routes so that url requests to any UI Router states would not be met with a 404, but instead always return the index.html file.
app.all('/*', function(req, res, next) {
// Just send the index.html for other files to support HTML5Mode
res.sendFile('index.html', { root: __dirname });
});
Then I added prefixes to my express routes, e.g. /api/posts/:post etc. Apparently express routes should not clash with any of the angular defined routes. Thanks to NormySan on reddit for informing me about this.