cookie that works with all folders - cookies

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 '/'

Related

Unable to set cookies on server side with Sveltekit

the title speaks for itself: From one moment to another, I am unable to set cookies from the server page of my Sveltekit project.
In the +page.server.js of my page I have an action in which I am setting a cookie with the set function. After that, when reloading the page, I am trying to retrieve the cookie with the get function inside the load function, but the cookie is undefined. I am quite convinced that it is not set at all, but I don't know why.
export const load = async ({ cookies }) => {
const myCookie = cookies.get('myCookie');
}
export const actions = {
default: async ({ cookies }) => {
//stuff
cookies.set('myCookie', true);
throw redirect(303, '/');
}
}
I specify that this is a procedure I have already done in other projects and it has always worked. What could be the problem? Thank you for your help.
UPDATE:
I don't know if it helps, but I want to specify that I am using Pocketbase and that a cookie is set in the hook.server.js of the project, which I can see in the browser and works correctly:
export async function handle({ event, resolve }) {
event.locals.pb = new PocketBase('http://127.0.0.1:8090');
event.locals.pb.authStore.loadFromCookie(event.request.headers.get('cookie') || '');
if (event.locals.pb.authStore.isValid) {
event.locals.user = serializeNonPOJOs(event.locals.pb.authStore.model);
} else {
event.locals.user = undefined;
}
const response = await resolve(event, {
transformPageChunk: ({ html }) => minify(html, minification_options)
})
response.headers.set('set-cookie', event.locals.pb.authStore.exportToCookie({ secure: false }));
return response
}

how can i see/modify the final url that ember http-proxy hits

Http-Proxy, like adapter, adds "/store-name" at the last of the proxy target that I specify.
I want to have complete control of the URL ,or atleast I should be able to add suffix to the url.
The file server/proxies/members.js looks like this for me.
var proxyPath = '/members';
module.exports = function(app) {
// For options, see:
// https://github.com/nodejitsu/node-http-proxy
var proxy = require('http-proxy').createProxyServer({});
proxy.on('error', function(err, req) {
console.error(err, req.url);
});
app.use(proxyPath, function(req, res, next){
// include root path in proxied request
req.url = proxyPath + '/' + req.url;
proxy.web(req, res, { target: 'http://localhost:8082/connection/testdb?tablename=' });
});
};
As the final url is this case looks like
"http://localhost:8082/connection/testdb?tablename=/members/"
instead i want
http://localhost:8082/connection/testdb?tablename=storename
P.S.: Is something like "buildURL=url" , possible in http-proxy
I'm unclear on exactly what you're trying to do, but take a look at the prependPath and ignorePath options to proxy.createProxysServer() (https://github.com/nodejitsu/node-http-proxy#options)
Update: Setup a proxyReq handler on the proxy object and you can manipulate the path any way you want. For example:
proxy.on('proxyReq', function(proxyReq, req, res, options) {
proxyReq.path = '/custom/path/here';
});

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

Ember server side pagination

I'm not trying to provide pagination within the view itself.
My API returns 500 records at a time and if there are more I'd like to automatically load them.
Although my solution right now does make the requests, I don't think it is the best way, but it does work.
App.StructureAdapter = App.ApplicationAdapter.extend({
findHasMany: function(store, record, url) {
// based on the normal `findHasMany` code
var host = Em.get(this, 'host'),
id = Em.get(record, 'id'),
type = record.constructor.typeKey;
if (host && url.charAt(0) === '/' && url.charAt(1) !== '/') {
url = host + url;
}
return this.findWithURL(this.urlPrefix(url, this.buildURL(type, id)), 1);
},
findWithURL: function(url, page) {
var that = this;
var completeUrl = url + "?page=" + page;
var nextPage = page + 1;
return this.ajax(completeUrl, 'GET').then(function(data) {
Em.Logger.log("calling then");
if (data.structures.length > 0){
that.findWithURL(url, nextPage);
}
return data;
});
}
});
My questions are:
Is there a better way to automatically get all of the pages for a given request?
How do I properly make sure the relationships are built. My Structure object has parent/children relationships on it, but only the first page of results is actually being associated correctly.
Update
Here is what my json response looks like:
{
"structures": [
{
"id": 6536,
"name": "Building",
"updated_at": "2013-05-21T07:14:54-06:00",
"person_id": 6535,
"notes": ""
},
... 499 more objects ...
]
}
It works properly, it loads the first group just fine. And I can adjust it in the extract/normalize methods if I need to.
Here is my normalize method as it is right now:
App.StructureSerializer = App.ApplicationSerializer.extend({
normalize: function(type, hash, prop) {
// adds the properly link to get children
hash.links = { "children": "structures" };
// change structure_id to parent_id
hash.parent_id = hash.structure_id;
delete hash.structure_id;
return this._super(type, hash, prop);
},
});
Again, the links makes it automatically know where to look for the has many relationship.
Looking at it closer, though the paginated pages actually do get called, they are not loaded into Ember data at all. So maybe if they did get loaded then the relationships would build properly.
Here's the best idea I have, I dunno how well it'd work and you might need to play around with it a bit.
In your StructureRoute, go ahead and return the model as normal, so:
App.StructureRoute = Ember.Route.extend({
model:function() {
return this.store.find('structure');
}
});
That'll fetch your first 500 objects and begin the route transition.
Then in your StructureController, fetch the other models using query parameters like this:
App.StructureController = Ember.ArrayController.extend({
init:function() {
this.loadNextPage(2);
this._super(); // this may not be necessary still, but the docs call for it
},
loadNextPage: function(page) {
var self = this;
var promise = this.store.find('structure',{page:page});
promise.then(function(structures) {
if(structures.get('length') < 500) {
self.loadNextPage(page + 1);
}
});
}
});
So when the StructureController initiates, it'll call the recursive function loadNextPage. This will keep running until it hits a page contains less then 500 models. Hopefully, that'll be the last page. By providing the second parameter to find, Ember should trigger a request to /structure?page=2. Inversely, you could do all of this in the route, if you don't mind the slow load time.
If at all possible, I would suggest modifying your API to add some pagination meta data to your request. Then you can use that metadata to control when to stop the recursive function. You can see how to handle metadata here.
Finally, I'm not sure if that's a typo in your json, but you may need to override your pluralization.
Anywho, hope that helps and I didn't overly simply the problem!
I really don't like this solution, but this does work. Please post if you have a much cleaner way of doing this.
Step 1: Load the Data into Ember Data
Since the data wasn't being loaded into Ember Data for the other pages I had to manually load it. I did that by adjusting the findWithURL function I created above.
findWithURL: function(url, page) {
var that = this;
var completeUrl = url + "?page=" + page;
var nextPage = page + 1;
var store = EditUserApp.__container__.lookup('store:main');
return this.ajax(completeUrl, 'GET').then(function(data) {
if (data.structures.length > 0){
that.findWithURL(url, nextPage);
}
store.pushPayload('structure', data);
return data;
});
},
I feel like there should be a cleaner way to do this, but it works.
Step 2: Rebuild the relationships
For some reason it didn't seem to be rebuilding the child/parent relationships. To take care of that I had to use the didLoad callback inside of the Structure model.
didLoad: function() {
var parent = this.get('parent');
if (parent) {
var that = this;
parent.get('children').then(function(children) {
children.addObject(that);
});
}
},
Any suggestions for how to improve this solution are welcome. Ideally I feel like there should be a better Ember way to handle this whole scenario.

Incorrect base URL for Backbone DELETE requests - uses relative instead of absolute URLs

TL;DR version:
Building a Phonegap app using Backbone, and have a model called Client and a collection called Clients. Using a Tastypie API to communicate with a separate server. When I run fetch(), the URL uses the correct absolute URL (something like http://127.0.0.1:8000/api/v1/client/1/, but when I run Client.destroy(), it uses a relative URL of file:///api/v1/client/1/. How can I make it use the absolute URL for deleting the object?
Long version:
I'm building a mobile app with Backbone.js that consumes a Django/Tastypie API, and I've run into some seemingly odd behaviour that I can't figure out.
I define a base URL for the server at the top of the file:
// Set the base URL for querying the API
baseUrl = 'http://127.0.0.1:8000/api/v1/';
I have the following model and collection:
// Client model
Client = Backbone.Model.extend({
urlRoot: baseUrl + 'client',
// Default values
defaults: {
id: '',
name: '',
mobile: '',
email: '',
notes: '',
operator: '',
date_client_joined: '',
address: '',
postcode: ''
}
});
// Client collection
Clients = Backbone.Collection.extend({
// Will hold Client objects
model: Client,
// Set URL
url: baseUrl + 'client/'
});
And the individual clients are rendered in a list using the following view:
// Client list item view
ClientListItemView = Backbone.View.extend({
tagName: 'li',
events: {
'click .delete': 'deleteclient'
},
render: function () {
// Render the client list item template
var template = _.template($('#client-list-item-template').html());
this.$el.html(template(this.model.toJSON()));
// Return the object
return this;
},
deleteclient: function () {
this.model.destroy();
return false;
}
});
Now, the app actually uses jQuery Mobile and each client has a Delete button next to it with a class of delete, so the deleteclient function is executed each time one of these buttons is clicked. I'm also using backbone-tastypie to iron out the inconsistencies between Backbone and Tastypie.
The deleteclient function is running, but it sends the HTTP DELETE request to a relative URL of file:///api/v1/client/1/ (as this is a Phonegap app, I'm just viewing the files locally). From the documentation setting urlRoot manually seems like the way to go, but doing so didn't seem to solve the issue. Running the fetch() function to populate the collection works absolutely fine, though - it uses the correct absolute URL.
So, my question is how can I override the default behaviour and ensure my HTTP DELETE request is sent to the correct URL?
By looking at your code it should work ok. The Model in backbone already has a url() function defined which should do this:
url: function() {
var base = _.result(this, 'urlRoot') || _.result(this.collection, 'url') || urlError();
if (this.isNew()) return base;
return base + (base.charAt(base.length - 1) === '/' ? '' : '/') + encodeURIComponent(this.id);
},
Can you use the debugger to see if it enters inside this code and what is the result of it? Mainly check the values from the _.result() calls...
Anyway, you can override the url property in your models rather than passing it in every call to destroy():
Client = Backbone.Model.extend({
url: function () { return baseUrl + 'client/' + this.id + '/'; }
// other code...
});
I found a solution, though I'm not entirely happy with it:
deleteclient: function () {
if (confirm('Are you sure you wish to delete this client?')) {
// Destroy the model
this.model.destroy({
url: baseUrl + 'client/' + this.model.get('id') + '/'
});
// Remove the view
this.remove();
}
}
Basically, if I explicitly pass through the URL to destroy(), that does the trick. It's a little annoying that I can't find a more DRY way to do this, so I'm open to any other method of doing the same thing.