Vue Router Webpack Dot in Params - url

I'm creating an app with NodeJS/Express for the back and VueJS for the Front using Vue Cli and webpack.
I'd like to know if there is a way to allow dot in params for my routes.
Here is what I get when i try with no config
Cannot GET /t/firstname.lastname
Here is my /src/main.js
import Vue from 'vue'
import App from './App.vue'
import VueRouter from 'vue-router'
import VueResource from 'vue-resource'
import VueAutosize from 'vue-autosize'
import Main from './components/Main.vue'
import Signin from './components/Signin.vue'
// We want to apply VueResource and VueRouter
// to our Vue instance
Vue.use(VueRouter)
Vue.use(VueResource)
Vue.use(VueAutosize)
const router = new VueRouter({
history: true
})
// Pointing routes to the components they should use
router.map({
'/t/:person': {
component: Main
},
'/signin': {
component: Signin
}
})
router.beforeEach(function (transition) {
if (transition.to.path === '/signin' && window.localStorage.length !== 0) {
transition.redirect('/')
} else if (transition.to.path === '/' && window.localStorage.length === 0) {
transition.redirect('/signin')
} else {
transition.next()
}
})
// Any invalid route will redirect to home
router.redirect({
'*': '/404'
})
router.start(App, '#app')

I was dealing with the same issue, even I'm late to the conversation maybe somebody will find useful the solution I found.
It appears to be webpack's fault.
If using vue-cli's webpack template you'll need to configure a proxy for the routes you need. For example in your case you'll need to add this to the config/index.js file:
...
dev: {
...
proxyTable: {
'/t/*.*': { // this will match all urls with dots after '/t/'
target: 'http://localhost:8080/', // send to webpack dev server
router: function (req) {
req.url = 'index.html' // Send to vue app
}
}
// Any other routes you need to bypass should go here.
}
...
},
...
This way webpack will proxy all requests to that url and don't treat these as files.

Add /something after params
eg: in your route
{
path: your-route/:paramname/something",
component: somecomponent,
}
After this, you should be able to access the route using this.$route.params.paramname

do below setting in webpack
devServer: {
historyApiFallback: {
disableDotRule: true
}
}

Related

Next.js rewrites + custom dynamical header for axios on the server-side

How i can do dynamical header for axios on the serve-side? I want to make functionality of cities, without edit nextjs folder structure. Rewrities from nextjs solves my problem, but I can't set the header for axios request functions on the server side. useRouter() hook returns non-proxied path.
// next.config.js
...
async Rewrites() {
return [
{
source: '/new-york/:path*',
destination: '/:path*',
},
]
}
...
Im tried use axios intreception function:
// destination _app.js
export default function AxiosInterceptors() {
...
const router = useRouter();
const asPath = router.asPath; // asPath return not non-proxied path, if i use url /new-york/blogs, here i see /blogs;
apiQr.interceptors.request.use(function (config) {
config.headers['city'] = asPath.includes('/new-york') ? '2' : '1'; // city id
return config;
}, function (error) {
return Promise.reject(error);
});
...
}
Im also tried set headers from NextJS _middleware.js but there is no access to axios requests and the axios interceptor function is not called there.
Where and how can I get a stable variable depending on the entered url on the server side so that I can adjust the axios headers?
I expect to get the proxied url in the axios interceptors instance as I showed above, but I get the proxied path.

HonoJS CORS with cloudflare worker

I'm starting with cloudflare worker and used the recommended routing framework HonoJS.
Now the documented way of implementing cors functionallity doesn't work for me on my developement machine (npm run dev). I didn't test it on production, since I need it to work on development environment.
The problem is: The OPTION request gets an 404 returned.
How do I set a global CORS configuration?
My code is currently this:
import { Hono } from 'hono'
import { cors } from 'hono/cors'
import { basicAuth } from 'hono/basic-auth'
import { default as register } from './register.js'
const app = new Hono()
app.use('*', cors())
const user = new Hono()
// also tried: user.use('/*', cors())
user.post('/register', register)
// Register route groups
app.route('/user', user)
export default app
Also tried following cors call:
cors({
origin: 'http://localhost:5173',
allowHeaders: ['X-Custom-Header', 'Upgrade-Insecure-Requests'],
allowMethods: ['POST', 'GET', 'OPTIONS'],
exposeHeaders: ['Content-Length', 'X-Kuma-Revision'],
maxAge: 600,
credentials: true,
})
Thank you very much for your time!
I fixed it by adding a wildcard for options.
app.use('*', cors({
origin: 'http://localhost:5173',
allowHeaders: ['Content-Type', 'Authorization'],
allowMethods: ['POST', 'GET', 'OPTIONS'],
exposeHeaders: ['Content-Length'],
maxAge: 600,
credentials: true,
}))
app.options('*', (c) => {
return c.text('', 204)
})

Rails Webpacker does not compile subdirectory

EDIT: Solution: make sure you spell the class-methods correctly. My error stemmed from typing contructor() within the class (please refer to the source-code of SocialShareModal.js.
Also, make sure your linter in your editor of choice works correctly! Mine did not. It would have spared me hours if it actually did :-)
I am running a Rails-application (ruby v 2.6.2 / Rails v 6.0.2) using webpacker. My JavaScript has been working like a charm, up until I tried putting component-related JS into a dedicated sub-directory of my app/javascript-folder.
This is what my JS-file-tree looks like:
javascript
├──channels
├──custom
│ ├──components (new & not working)
│ ├──config
│ ├──helpers (these are working somehow)
│ └──pages
├──config
└──packs
In application.js I import a custom Router.js, initialize it with my custom routes to then, on various subpages, initialize my custom JS-classes. It all worked so far (and continues to) with classes which live in the helpers-folder, however the classes which live in the new components-folder won't work. I am unsure if they are even picked up and compiled by webpack.
application.js:
import routes from '../custom/config/routes'
import Router from '../custom/Router'
require("#rails/ujs").start()
require("turbolinks").start()
require("#rails/activestorage").start()
require('channels')
...
class myApp {
constructor() {
this._initRouter()
}
/**
* Initializes the router and its routes
* #private
*/
_initRouter () {
this._router = new Router(routes)
}
}
document.addEventListener('turbolinks:load', function() {
window.myApp = new myApp()
})
routes.js:
import Page from '../pages/page'
// Frontend
import Root from '../pages/frontend/root'
import SignInPage from '../pages/frontend/signInPage'
// Dashboard => Admin
import AdminAccountsEditPage from '../pages/dashboard/admin/accounts/edit'
// Dashboard => User
import WelcomePage from '../pages/dashboard/user/welcomePage'
export default [
// Frontend
['', Root],
['accounts/sign_in', SignInPage],
// Dashboard => Admin
['admin/accounts/(.*)', AdminAccountsEditPage],
// Dashboard => User
['dashboard/willkommen', WelcomePage],
// Catch all for when there is no exact match:
['(.*)', Page]
]
Router.js:
/* global location */
export default class Router {
constructor(routes) {
this.routes = routes
this.handleRoute()
}
/**
* Checks if there's a javascript for the current route, requires the class and
* instantiates it
* #private
*/
handleRoute() {
let { pathname } = location
// Remove leading and trailing slashes
pathname = pathname.replace(/^\/|\/$/g, '')
// Go through routes and check which one matches
for (let i = 0; i < this.routes.length; i++) {
const [route, PageClass] = this.routes[i]
const regexp = new RegExp(`^${route}$`, 'i')
if (route === true || regexp.test(pathname)) {
this.currentPage = new PageClass()
break
}
}
}
}
Page.js:
import tippy from 'tippy.js'
import 'tippy.js/dist/tippy.css'
import FlashMessageHelper from '../helpers/FlashMessageHelper'
import AddToWishlistHelper from '../helpers/AddToWishlistHelper'
import SocialShareModal from '../components/SocialShareModal' // importing it
export default class Page {
constructor() {
new tippy('[data-tippy-content]')
new FlashMessageHelper() // working
new AddToWishlistHelper() // working
new SocialShareModal() // NOT working (not initializing)
}
}
SocialShareModal.js
export default class SocialShareModal {
get modalSelector() { return '.modal' }
get triggerModalSelector() { return '.js-trigger-modal' }
get copyToClipBoardButtonSelector() { return '.js-copy-to-clipboard' }
contructor() { // As you can see, the error resided here
console.log('SocialShareModal constructor called')
this.init()
}
init() {
let modalButton = document.querySelector(this.triggerModalSelector)
modal.addEventListener('click', handleModalTrigger)
window.addEventListener('scroll', this.handleTestScroll)
}
handleModalTrigger() {
let modal = document.querySelector(this.modalSelector)
modal.classList.add('is-active')
}
}
I've done lots of reading, but can't seem to figure out the issue, as I'm not super-comfortable with webpack. Any suggestions on how to solve this?
Edit: added source-code for application.js, routes.js, Router.js, Page.js & SocialShareModal.js to provide more context.

Migrate Google Workbox setDefaultHandler // setCatchHandler from v2 to v3

I'm trying to migrate my old code from google workbox v2 to workbox v3, and i can't use workbox.routing.registerNavigationRoute because my default route '/' (which is where my appshell is) is a runtime cache (because it's for a multilingual website https://www.autovisual.com with languages put in subfolder '/fr', '/es' ... with a unique Service-Worker scoped at '/').
This is the v2 code :
workboxSW.router.setDefaultHandler({
handler: ({
event
}) => {
return fetch(event.request);
}
});
workboxSW.router.setCatchHandler({
handler: ({
event
}) => {
if (event.request.mode === 'navigate') {
return caches.match('/');
}
return new Response();
}
});
It seems pretty basic : the goal is to catch all request 'navigate' that didn't match any other route and send the cached version, network first, of the url '/'.
For the info in the client js i use :
if ('serviceWorker' in navigator) {
window.addEventListener('load', function() {
caches.open('rootCacheNetworkFirst').then(function(cache) {
cache.match('/').then(function(response) {
if (!response) {
cache.add('/');
}
});
});
navigator.serviceWorker.register('/sw.js', {
scope: "/"
});
});
}
I can't find any example with the new v3 workbox.routing.setDefaultHandler and workbox.routing.setCatchHandler and i'm stuck :(
I don't think that using either setDefaultHandler or setCatchHandler is relevant for that described use case.
To accomplish what you describe, add the following code to your service worker file after all other routes are registered. (In Workbox v3, the first-registered-route takes precedence.) You just need to configure a NavigationRoute and register it:
const networkFirst = workbox.strategies.networkFirst({
cacheName: 'your-cache-name',
});
const navigationRoute = new workbox.routing.NavigationRoute(networkFirst, {
// Set blacklist/whitelist if you need more control
// over which navigations are picked up.
blacklist: [],
whitelist: [],
});
workbox.router.registerRoute(navigationRoute);

Request from Ember front to Rails back is not happening

I am implementing a front-end in ember 1.13 with a Rails back-end and having the following problem:
After the user is authenticated, I don't seem to be able to retrieve the user's record from the back-end. The browser debugger does not even show a request being made. This is code:
// app/services/session-user.js
import Ember from 'ember';
const { inject: { service }, RSVP } = Ember;
export default Ember.Service.extend({
session: service('session'),
store: service(),
loadCurrentUser() {
currentUser: {
var userId = this.get('user_id');
if (!Ember.isEmpty(userId)) {
return this.get('store').findAll('user', userId);
}
}
}
});
There is a login controller which handles the authentication. But the code for getting the data is in the applications's route:
// app/routes/application.js
import Ember from 'ember';
import ApplicationRouteMixin from 'ember-simple-auth/mixins/application-route-mixin';
const { service } = Ember.inject;
export default Ember.Route.extend(ApplicationRouteMixin, {
sessionUser: service('session-user'),
beforeModel() {
if (this.session.isAuthenticated) {
return this._loadCurrentUser();
}
},
sessionAuthenticated() {
this._loadCurrentUser();
},
_loadCurrentUser() {
return this.get('sessionUser').loadCurrentUser();
},
});
For extra measure I am defining the session store:
// app/session-stores/application.js
import Adaptive from 'ember-simple-auth/session-stores/adaptive';
export default Adaptive.extend();
If there are files I should post, please let me know.
Any hints will be highly appreciated as I am rather new to ember. I have spent several hours researching without luck, as things seem to have changed quite a lot throughout versions.
Look at your service code.
var userId = this.get('user_id');
if (!Ember.isEmpty(userId)) {
return this.get('store').findAll('user', userId);
}
I don't see code that you provided in question where you setting up user_id variable. So if user_id not defined then if statement won't get executed because of !.

Resources