Remove unnecessary URL parts/parameters - ember.js

I've got a blog with article-urls like this http://ali.dj/blog/unlimited-fps-in-unity-editor
My old blog had URLs like this: http://ali.dj/blog/unlimited-fps-in-unity-editor/comment-page1 etc.
When the article is valid but everything following it is unnecessary I would like to strip out parts and parameters after the URL.
This http://ali.dj/blog/unlimited-fps-in-unity-editor/comment-page1
or this http://ali.dj/blog/unlimited-fps-in-unity-editor/comment-page1?ref=foo
becomes this http://ali.dj/blog/unlimited-fps-in-unity-editor
Currently I've got a catch-all route which will redirect the user to the error-page
How can I strip out unnecessary parts?
Here's the router.js I currently use for articles:
this.route('blog', { 'path' : 'blog/'}, function() {
this.route('post', { 'path' : ':permalink' })
this.route('not-found', { 'path' : 'not-found'})
});
// Error routes
this.route('not-found', { path : '/not-found'})
this.route('catch-all', { path : '/*path'}) // redirects to not-found

Related

Adonis.js api delete route is not working

I tried to hit a specific route:
http://127.0.0.1:3333/store/products?productId=4
but the server give me this error:
"message": "E_ROUTE_NOT_FOUND: Cannot DELETE:/store/products",
"stack": "HttpException: E_ROUTE_NOT_FOUND: Cannot PATCH:/store/products\n
In addition to the points raised by #crbast :
your code seems to hit the HTTP PATCH method (https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PATCH) instead of the HTTP DELETE you expect
You are not hitting the right url and your route is wrong.
The right url with your route.js is :
http://127.0.0.1:3333/store/products/4
^- Product id
and the route :
Route.delete('/products/:productId', 'ProductsController.delete')
// ^- use : for url parameter
Routing explanation
Body data & url parameters are totally different.
Please read : What is the difference between URL parameters and query strings?
Body data
Request body (json).
Documentation : https://preview.adonisjs.com/guides/http/form-submissions#reading-form-data
Example url :
http://127.0.0.1:3333/products?name=hello
Route example :
Route.post('/products', 'MyController.myFunction')
Controller :
public async myFunction ({ request }: HttpContextContract) {
const data = request.only(['name'])
// ...
}
Url parameter
Specify dynamic url parameter.
Documentation : https://preview.adonisjs.com/guides/http/routing#dynamic-urls
Example url :
http://127.0.0.1:3333/products/1
Route example :
Route.post('/products/:id', 'MyController.myFunction')
Controller :
public async myFunction ({ params }: HttpContextContract) {
const id = params.id
// ...
}

URL management with Django, GraphQL, Apollo and VueJS

As said in the title, I'm using Django, GraphQL, Apollo and VueJS in my project.
I'm developping it as a SPA (Single Page Application).
Everything works fine, until I hit the F5 button and refresh the page. Indeed, it shows an unknown page. The thing is it is VueRouter that is managing the SPA and it works fine. But when I press F5, that is Django that tries to serve a page for the current URL and since it doesn't know it, it can't serve the appropriate page.
I know I can set the VueRouter 'history' mode, which I did, and add a URL to Django that serves index.html whatever the URL is.
My problem is the following :
When I'm on a particular form view (i.e : a User form view) my URL is the following :
http://localhost:8000/user
Since I'm using GraphQL for my API, the retrieved data is not based on the URL. In fact, that is my VueJS component that says : Hey Apollo, run that GraphQL to retrieve the User I want.
So when I refresh, yes it serves the User form view..but empty.
The question is : How could I solve this ?
For clarification purposes, here are some code samples :
My Django URLs :
# (... other imports here ...)
from .schema import schema
urlpatterns = [
path('admin/', admin.site.urls),
path('graphql', csrf_exempt(GraphQLView.as_view(graphiql=True, schema=schema))), # 'schema' is the main GraphQL schema
path('', TemplateView.as_view(template_name='index.html')),
re_path(r'^.*$', TemplateView.as_view(template_name='index.html')) # I saw that many times to serve the page whatever the URL is when refreshing the page
]
My Vue Router :
export default new Router({
mode: 'history',
routes: [
{ path: '/', name: 'MainApp' },
// ...
{ path: '/users', name: 'UserList', component: UserList },
{ path: '/user/create', name: 'UserFormCreate', component: UserForm, props: true },
{ path: '/user', name: 'UserFormView', component: UserForm, props: true },
{ path: '/user/edit', name: 'UserFormEdit', component: UserForm, props: true },
// Same pattern for other models like 'Group' ...
]
My Example VueJS Component :
<script>
import {
// ...
USER_QUERY,
// ...
} from '../../graphql/base/user.js'
export default {
name: 'UserForm',
props: {
userId: Number,
editing: {
type: Boolean,
default: false
}
},
apollo: {
user: {
query: USER_QUERY,
variables () { return { id: this.userId } },
skip () { return this.userId === undefined },
result ({ data }) {
this.form.username = data.user.username
this.form.firstName = data.user.firstName
this.form.lastName = data.user.lastName
}
}
},
data () {
return {
form: {
username: '',
password: '',
firstName: '',
lastName: ''
},
// ...
}
},
methods: {
// ...
}
I have to mention that I've seen more or less related topics but that doesn't solve my problem.
Thanks in advance for your help !
Edit your route paths to use params. For example:
{ path: '/user/:userId', name: 'UserFormView', component: UserForm, props: true }
Now, the app will interpret any number following the user/ path as a prop called userId. (props: true is important here for using the params as props.)
The only other change you need to make is adjusting your router-links to include the id as well (Ex.: http://localhost:8000/user/1) so that when the page is refreshed, there will be a param to read.

Regex for route work incorrect and return error 404

I have custom regex for match correct username:
^(?=.{5,20}$)[a-zA-Z](?:[a-zA-Z0-9_]*[a-zA-Z0-9])?$
See demo
Here you can see my routes list:
Route::middleware(['userActivity'])->group(function () {
Route::group(['prefix' => '{nickname}','where' => ['nickname' => '^(?=.{5,20}$)[a-zA-Z](?:[a-zA-Z0-9_]*[a-zA-Z0-9])?$']], function ($nickname) {
Route::name('user.')->namespace('User')->group(function () {
Route::middleware(['auth', 'company'])->group(function () {
Route::namespace('Vacancy')->group( function () {
Route::prefix('vacancy')->name('vacancy.')->group( function () {
Route::get('/manage', "VacancyController#manage")->name('manage');
Route::post('/save', "VacancyController#save")->name('save');
});
});
});
});
});
});
In this case when I go to route user.vacancy.manage:
http://website.com/user_1544080981/vacancy/manage
Return error:
404 Page Not Found
When I change my regex to:
^(?=.{5,30}$)[a-zA-Z](?:[a-zA-Z0-9_]*[a-zA-Z0-9])?$
Note: Changed in regex only min and max length from {5,20} to {5,30}
Generaly when I see to part of url after domain name url length == 30
user_1544081143/vacancy/manage
But regex must work only for user nickname instead of to part url without domain name. Where I have any errors in my routes?
Regular expression, this is a better way then above in my opinion.
Route::any('{all}', function(){
return 'It Works';
})->where('all', '.*');
Using the Route::fallback method, you may define a route that will be executed when no other route matches the incoming request. Typically, unhandled requests will automatically render a "404" page via your application's exception handler. However, since you may define the fallback route within your routes/web.php file, all middleware in the web middleware group will apply to the route. Of course, you are free to add additional middleware to this route as needed:
Route::fallback(function () {
//
});

Ember Data use different URL for requests

I am beginner for ember.js. I am tried to use ember data for restful api. However there is some convention on the path. For example App.Post.find() corresponding to http://www.example.com/posts.
However due to my application current pattern, all my list of data is listed under /post/list, what shall i do? here i am using post not posts and not using /posts but /post/list.
Please help.
It's simple enough to change how the adapter builds the url. You just extend the current adapter and override the methods that build the url. In your case I am setting the application adapter (meaning it would apply to all types). I wasn't positive how the url should have been built when you supply a particular id, but I'm pretty sure this is enough to get you started, and you can play the string manipulation game from this point.
App.ApplicationAdapter= DS.RESTAdapter.extend({
pathForType: function(type) {
var camelized = Ember.String.camelize(type);
return camelized; //Ember.String.pluralize(camelized);
},
buildURL: function(type, id) {
var url = [],
host = Em.get(this, 'host'),
prefix = this.urlPrefix();
if (type) { url.push(this.pathForType(type)); }
url.push('list');
if (id) { url.push(id); }
if (prefix) { url.unshift(prefix); }
url = url.join('/');
if (!host && url) { url = '/' + url; }
return url;
}
});
Example: http://emberjs.jsbin.com/OxIDiVU/690/edit

cookie that works with all folders

I have a cookie that is on every page of my site. It works fine when the address is like this.
http://mydomain.com/index.html or whatever.
but when I have a page that is in a folder like this
http://mydomain.com/folder/page.html
instead of using the cookie that I have set for all the other pages it creates a new cookie just for that folder. Is there any way to keep the same cookie for all folders? Or I'm I just doing something terrible wrong?
Thanks
my code -- I have this in a external js. file
$(document).ready(function(){
var cookie = $.cookie('cookiename');
if (cookie) {
}
else {
$.cookie('cookiename', 'cookievalue');
}
});
$(document).ready(function() {
$('.watevevever').click(function() {
var va = $('#watev').css('display');
if (va == 'none'){
$('#watev').fadeIn("slow");
$.cookie('cookiename', 'cookievalue');
}
else {
$('#watev').fadeOut("slow");
$.cookie('cookiename', 'cookievalue');
}
});
var va = $.cookie('cookiename');
if (va == 'cookievalue') {
$('#watev').css("display","none");
};
});
If you are using this plugin for jQuery (and its source is here), it seems, by looking at the source, that you can pass some additional parameters as an object, as a third parameter to the $.cookie method.
For instance, from this tutorial, you can add an expiration date :
$.cookie('the_cookie', 'the_value', { expires: 7 }); // set cookie with an expiration date seven days in the future
Looking at the source, you have this portion of code :
var path = options.path ? '; path=' + (options.path) : '';
var domain = options.domain ? '; domain=' + (options.domain) : '';
var secure = options.secure ? '; secure' : '';
So, I suppose you can use a "path" attribute in the object given as third parameter, like, for instance :
$.cookie('the_cookie', 'the_value', {path: '/'});
Of course, this '/' is if you want to set to cookie for every paths on your domain -- which seems to be the case.
You can probably also set some other options, like 'domain', if you want to use subdomains, btw...
$.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
the optional parameters includes 'path' .. which should be '/'