How to configure vue-router to ignore calls to one route? - vue.js

Let's say I have 3 apps A, B and C.
A is the parent app which resides in the root directory of the server. B and C is under /apps/B and /apps/C respectively.
Navigating to /apps/B loads the correct app, but navigating to /apps/B/xyz redirects me to / which is the parent app A.
How do I configure vue-router to allow all calls to /apps to passthrough along with their corresponding query params?
Something like:
router.beforeEach((to, from, next) => {
if (to.fullPath.includes("/apps/")) {
window.location.href = to.fullPath;
}
next();
});

You should set the proper publicPath in your vue.config.js for the B and C applications - otherwise they will assume a deployment inside the root folder of the domain.

Related

Is there way to route to home from a separate app hosted in a sub directory?

I have a vue js webapp which is hosted in www.example.com/app and the home page of the application is hosted in www.example.com as a separate vue js app using nginx. whenever the user hits, www.example.com/app/home I want to redirect to www.example.com.
right now I am doing,
//router.js
{
path: "/home",
beforeEnter(to, from, next) {
window.location.href = "https://www.example.com";
}
},
inside the route.js of example.com/app to achieve this. But in the localhost and the dev environment, this method won't work for obvious reasons. Is there a more convenient way to do this?
I think you can redirect with relative URL.
window.location.href = "/";

How to change express router path without changing URL?

I am statically serving my site from one directory. I have one dynamic route for setting the URL parameter roomCode. I want all routes to this path to serve the root index page without changing the URL on the client (that way I can still use the roomCode in my JavaScript).
Here is what I currently have:
// direct rooms to the index page
app.use('/room/:roomCode([A-Z]{4})', (_, res) => {
res.sendFile(path.join(__dirname, 'dist/index.html'))
})
// serve from the dist build
app.use(express.static(path.join(__dirname, 'dist')))
Instead of manually sending the dist/index.html file, I would like to simply change the route path to / for the following middleware and let the static server send the file. Something like this:
// direct rooms to the index page
app.use('/room/:roomCode([A-Z]{4})', (_, res, next) => {
req.path = '/'
next()
})
// serve from the dist build
app.use(express.static(path.join(__dirname, 'dist')))
This way, when the static middleware is reached, it believes the path was /, so it will serve the index page at the root.
Is this possible?
To reroute a request, you must change req.originalUrl to the new route, and then send it to the router handler with app._router.handle(req, res, next).
// direct rooms to the index page
app.use('/room/:roomCode([A-Z]{4})', (req, res, next) => {
// this reroutes the request without a redirect
// so that the clients URL doesn't change
req.originalUrl = '/'
app._router.handle(req, res, next)
})
// serve from the dist build
app.use(express.static(path.join(__dirname, 'dist')))
The documentation for req.originalUrl is a little confusing. It says:
This property is much like req.url; however, it retains the original request URL, allowing you to rewrite req.url freely for internal routing purposes.
This sounds like if you change req.url, it will change how it is routed. However, it does not. It does allow you to change it and then manually check it in latter middleware. But the middleware will still be called based on the original URL. Therefore, we need to overwrite the original URL and send it back through the router.

Vue - Load External Components From Another Site

I am trying to retrieve a vue component from an external site and load it in my app and cannot for the life of me figure this out.
Here is the full scenario;
Site A (Internally Hosted Site) loads a VueJS application
Site A requests a VueJS component from Site B (Internally Hosted Site, different sub domain)
Ideally, Site B would consist of .vue files either in their native .vue format or precompiled (maybe vue-cli for this?)
Site A loads and renders the components in the application
Let's say I have a very simplistic component I want to load from Site B;
{
"template": "<div><span>{{message}}</span></div>",
"data": function() {
return { "message": "Hello World" };
}
}
I've tried the following this with mixed results;
Inside my index.ts (using TypeScript)
Vue.component('my-external-component', () => (Vue as any).http.get("http://test.local/test.js"));
and inside my .vue file
<my-external-component></my-external-component>
This results in this comment being added to the DOM
<!--function (a, b, c, d) { return createElement(vm, a, b, c, d, true); }-->
however adding
<component :is="my-external-component"></component>
Results in an empty comment being added to the DOM
<!---->
I have also done a couple variations of this including using the cli to compile the template into a js file and attempting to load that, weird error about not being able to access template.trim or something along those lines.
Given that your component definition is (or was) JSON and component data should be a function, you should transform the result before resolving the async component.
For example (using fetch because I don't know what Vue.http is)
Vue.component('MyExternalComponent', () =>
fetch('http://test.local/test.json').then(res => res.json()).then(defn => ({
...defn,
data () { // transform defn.data into a function
return defn.data
}
}))
)
JSFiddle demo here using their /echo/json service to simulate the external component definition.
Exporting a component definition from a remote .js file would be tricky.

Vue js how to set a default router path to navigate when the web app loads

I have a project it's routing strucher is like this.
1. /
2. admin-panel/:type
2.1 create-user
2.2 update-user
2.3 etc...
3. forgot password
My problem is if someone come to the admin-panel/:type,he has to route to the create-user
by default.
I used a tricky way for this which is create root route under the admin-panel/:type
like this
2.admin-panel
2.1 /
2.2 create-user
But this doesn't work this time since the admin-panel has a parameter called type.
I want if someone comes to the admin-panel he should directed to the create-user by default. How do I achieve this?
I've to add redirect property to the admin-panel route.
Personally for these cases I use an afterEach hook in the routes file:
router.afterEach((to, from) => {
let exist = false
for (let i in this.a.options.routes) {
if (this.a.options.routes[i].name === to.name) {
exist = true
}
}
if (!exist) {
this.a.push({
name: from.name
})
}
})
You can use another hook as beforeEach (I do not remember exactly why we use after). Basically the goal is to go through the list of routes, if it does not exist, it returns you to the route you are currently on, which really means that you do not notice any changes, it just does not change the route.

How should routing html pages be done for website?

I'm using MEAN stack. For example, if I click on a item, how does it route it's item page like *****.com/item/[id]? How does it go to that item page for that id? Is this done using node and express?
Call the route and send file, somelike this...
app.get('/item/:id', function (req,res){
console.log(req.params.id); be show the param id
res.sendFile('page.html', {id: req.params.id});
)};
More aboute routes
Okay, you need to understand routing mechanism of single page applications. Now you should be aware that your root path that is '/' will be served by express
app.get('/', function(req, res) {
res.sendFile('index.html', { root: path.join(__dirname, '../public') });
});
As soon as your index.html is served to the client, Angular will take over all the routing. You must use a routing solution for that(ui state or ngRouter). if you want to go to a particular route in angular containing some id you can create a route like this(assuming you are using ui-state router)-
$stateProvider
.state('user', {
url: "/user/:id",
templateUrl: "/angular/users/views/user.html",
controller: "UserCtrl"
});
In your html file you will write -
<a ui-sref="user({id: userId})">
Here userId is the id you want to pass to the route.
Hope it helps!