How to do routing with Electron and Vanilla Javascript - javascript

I have been looking for ways to find a way to make a single page application with vanilla javascript only but sadly I could not find one.
I found this code in a tutorial on how to make a SPAs, however the issue is location.pathname returns not the URL path but the file path instead with Electron. This bit of code is integral to make the routing work. And I don't wanna use any frameworks.
const router = async () => {
const routes = [
{ path: "/", view: console.log("Viewing /") },
{ path: "/login", view: console.log("Viewing login") },
{ path: "/dashboard", view: console.log("Viewing dashboard") },
];
const potentialMatches = routes.map((route) => {
return {
route: route,
isMatch: location.pathname === route.path,
};
});
};
window.addEventListener("load", () => {
router();
});
Is there a way I could retrieve the URL path and inject it to my index.js?

Related

Angular SSR, Dynamic Page Won't Load - Status 504

Code: http://github.com/dbots-co/website
Directly connecting to a dynamic route (dashboard, bot page), seems to not work. However, directly connecting to docs does work.
This only happens when using Angular 10 Universal SSR.
Not Working: https://dbots.co/bots/774811448576573480
Working: https://dbots.co/docs/get-started
bot-page.component.ts:
async ngOnInit() {
await this.service.init();
this.user = this.service.getBot(this.id);
this.bot = this.service.getSavedBot(this.id);
if (!this.user || !this.bot)
return this.router.navigate(['']);
this.seo.setTags({
description: this.bot.listing.overview,
titlePrefix: this.user.username,
titleSuffix: 'DBots',
url: `bots/${this.id}`
});
this.analytics.botPageView({ botId: this.user.id });
this.themeService.setNavbarBackground('var(--background-secondary)');
document
.querySelector('.navbar')
.setAttribute('style', `margin-bottom: -5px;`);
}
app-routing.module.ts:
const routes: Routes = [
...
{ path: 'bots/:id', component: BotPageComponent },
...
];

Next Js Custom Routes and SSR

I am using apollo with next and recently I noticed that custom routes breaks SSR. Usually if you navigate through pages apollo caches the query and when you are on the page the next time, it serves everything from cache. However with custom routes, the cache is never used.
I also noticed that when I click on these pages, an error flashes in the console. But it goes away very fast and I wasn't able to copy it here.
Server.js
//
server.get('/about-us', (req, res) => app.render(req, res, '/about'));
server.get('/about', (req, res) => res.redirect(301, '/about-us'));
Menu Click Handler
const navigate = link => () => {
Router.push(link);
};
Menu Items
export const menu = [
{
name: 'Home',
url: '/',
},
{
name: 'Catalogs',
url: '/catalogs',
},
{
name: 'Shop',
url: '/shop',
},
{
name: 'Wholesale',
url: '/wholesale',
},
{
name: 'About Us',
url: '/about-us',
prefetch: true,
},
{
name: 'Contact Us',
url: '/contact-us',
prefetch: true,
},
];
Based on a suggestion from nextjs spectrum I tried prefetching custom pages in the TopNav Component but it didn't work.
const prefetch = url => {
if (process.browser) {
console.log('prefetching these urls', url);
Router.prefetch(url);
}
};
useEffect(() => {
menu.forEach(menuItem => {
if (menuItem.prefetch) {
prefetch(menuItem.url);
}
});
}, []);
I was able to figure out the problem. This is not really well documented but you need to prefetch the component. So for my case instead of prefetching /about-us I should have prefetched /about.
That's why there is as prop in the link component. Nextjs 9 just got released which fixes this issue.
https://nextjs.org/blog/next-9#dynamic-route-segments
For nextjs 9 you can save your file as [pid].js and it will catch all paths in a specific route. i.e for /products/test-product you have to create folder products and inside that add [pid].js.
I needed to query for product based on slug so I added this and voila, I have access to the slug inside my component.
Product.getInitialProps = async ({ query }) => {
return { slug: query.pid };
};
These issues were pretty frustrating before next 9 but it's heavily simplified and it helped me fully remove server.js.

Axios returns undefined in nested Vue JS (Laravel API)

I'm having a lot of trouble with Axios when using nested routes in Vue JS.
I have found that if my component is at the root ("/"), as with the "Accounts" component below, then Axios loads the data correctly, no problems here.
But if I went to the "Campaigns" component, which is nested at "/accounts/:account_id" then Axios stops working. In fact, it doesn't return any data at all. However, the API is valid, as Postman correctly returns the data.
So whenever I move a component into a nested URL, Axios stops working. I have no idea why this is happening, and I cannot find any solutions online. I'm sure it must be simple, but I can't see it.
app.js (Includes routes)
const router = new VueRouter({
mode: 'history',
routes: [
{
path: '/',
name: 'accounts',
component: Accounts
},
{
path: '/accounts/:account_id',
name: 'campaigns',
component: Campaigns
},
],
});
Campaigns Component
<script>
import axios from 'axios'
export default {
data() {
return {
accountID: null,
campaigns: [],
campaignsMeta: {},
};
},
mounted() {
this.accountID = this.$route.params.account_id;
this.fetchCampaigns();
},
methods : {
fetchCampaigns(page = 1) {
const AuthStr = 'Bearer '. concat(this.apitoken);
axios.get("api/account/" + this.accountID + "?page=" + page)
.then(({data}) => {
this.campaigns = data.data;
this.campaignsMeta = data.meta;
});
}
},
}
</script>
For anyone who is experiencing a similar problem in the future, I made the error of using a relative URL and not an absolute URL for the Axios Get request.
Original Code
axios.get("api/account/" + this.accountID + "?page=" + page)
.then(({data}) => {
this.campaigns = data.data;
this.campaignsMeta = data.meta;
});
Correct Code
axios.get("/api/account/" + this.accountID + "?page=" + page)
.then(({data}) => {
this.campaigns = data.data;
this.campaignsMeta = data.meta;
});
Note the "/" at the start of "/api/account" indicating an absolute path, not relative.
The reason this is important is because:
For relative URLs, the API request would be appended to the end of the current page URL, so the API request on the Accounts component would have been: /accounts/:account_id/api/account (which is wrong!)
For absolute URLs, the API request is made from the domain name, so the API request on the Accounts component is: domain.com/api/account (correct!)
Thanks!

Navigo JS Router - Duplicate routing issue

Not sure what the issue is but my Navigo router is duplicating routes.
The Router:
this.Navigo.hooks({
before: (done, params) => {
// some tomfoolery
done();
}
});
this.Navigo.on({
'/:region/travel': (params) => {
// import Travel module
// some nonsense
},
'/:region/travel/car': (params) => {
// import TravelCar module
// some nonsense
}
)};
this.Navigo.resolve();
The Problem
this.Navigo.navigate('/london/travel/car');
Navigating to /london/travel/car is also triggering the route for /london/travel and thus causing all kinds of twaddle.
Is this standard behaviour? If not, what could be wrong?
I could rewrite the routes so they don't collide e.g. /london/travel-by-car, but I really don't want to if I can avoid it.
UPDATE 1:
I tried switching the order of routes but makes no difference. I did this by declaring the longest travel routes first, /:region/travel/car, and the smallest, /:region/travel, last.
UPDATE 2:
The more I look into this, the more I'm convinced this cannot be achieved with Navigo. Navigo do not support nested routes. If somebody could confirm that my routes are in fact 'nested', I will use an alternative routing library that does support them.
My code is a little different, but works the way you expect:
var router = new Navigo("/");
var render = (content) => (document.querySelector("#app").innerHTML = content);
router
.on('/:id', ({ data }) => {
setuserId(data.id)
if (verifiedUser) {
console.log("User verified");
} else {
console.log("User NOT verified");
}
rendertemplate(userDataURL(), "#landing-template", "#app")
})
.on('/:id/q', ({ data }) => {
// Example - flaging a send with 's' from 'SMS', perhaps a diff flow?
setuserId(data.id)
rendertemplate(userDataURL(), "#landing-template", "#app")
console.log("Source was a QRcode");
})
.on('/:id/q/t', ({ data }) => {
// Example - flaging a send with 's' from 'SMS', perhaps a diff flow?
setuserId(data.id)
rendertemplate(userDataURL(), "#landing-template", "#app")
console.log("Source was a QRcode in a Train");
})
This will give me a single discreet ".. verified"/"Source was a QRcode"/"Source was a QRcode in a Train" console.log response.
B

Nested resources and path

I'd like to nest resources in Ember, but to be able to access them with a short URL.
For example: mysite.com/admin will open the route: /routes/profiles/settings/admin
Is it possible to do something like that using Ember?
I'm currently using Ember 1.7 with Ember App Kit.
I tried the following but it doesn't work:
var Router = Ember.Router.extend();
Router.map(function () {
this.resource('profile', function () {
this.resource('profile.settings', { path: '/settings' }, function () {
this.resource('profile.settings.admin', { path: '/admin' });
);
});
Thanks.
Your code doesn't work because your inner most resource is inheriting the /profile path from the outer most resource and /settings from the middle resource. If you want it to be just plain /admin, you'd have to do something like this:
this.resource('profile', { path: '' }, function() {
this.resource('profile.settings', { path: '' }, function() {
this.resource('profile.settings.admin', { path: '/admin' });
});
});
However, this is going to get pretty hairy when you have more routes that each want top-level paths. You might find it easier to just declare a admin route at the top level, then redirect using the redirect hook in the route.

Categories

Resources