lundi 27 juin 2016

Default settings for all jQuery ajax calls


I have a JS client (app.domain.com) that connects to an API written in rails and grape (api.domain.com). CORS is set up and I have a shared cookie between the two domains as the log in is performed on the api.domain.com server.

This JS application is using Spine.js so everything is written in CoffeeScript. So to send a delete request I just use:

    @item.destroy

This will send a DELETE request to the API. However the cookie is not sent along with the request header so I had to change the above line of code to this one:

    $.ajax({
        url: "http://api.domain.com/tasks/" + @item.id,
        type: "DELETE",
        crossDomain: true,
        xhrFields: {
            withCredentials: true
        }
    })

And this works perfectly. It will send a response header "Access-Control-Allow-Credentials: true" along the request so the cookie is submitted and the action is authenticated.

However, this way I will have to write lines of code for each request which is really time consuming and also voids the benefits of the Spine framework.

I know that it's possible to set default ajax settings in jQuery so that every subsequent ajax call will be using these settings. So I've tried:

jQuery.ajaxSetup({
headers: {
    "X-Requested-With": "XMLHttpRequest",
    "Access-Control-Allow-Credentials": "true"
    }, crossDomain: true
});

Which are basically the same settings I would put for each ajax call manually. However this approach doesn't work though I see these headers in the request sent to the API (through firebug).

Am I missing something?

Thanks in advance!

Dav


Aucun commentaire:

Enregistrer un commentaire