Welcome Guest, Not a member yet? Register   Sign In
CSRF with fetch API
#3

(This post was last modified: 07-07-2020, 12:54 PM by Leo.)

(07-07-2020, 10:26 AM)MGatner Wrote: See this: https://github.com/codeigniter4/CodeIgni...ssues/2454

Basically, CSRF behavior differs when it detects an AJAX call, but `fetch` calls are indistinguishable from regular HTTP requests. You can work around this by providing the headers with your `fetch` command:

fetch(url, {
    method: "get",
    headers: {
      "Content-Type": "application/json",
      "X-Requested-With": "XMLHttpRequest"
    }

Thanks MGatner! But I've no problems at all with the "get" method, fetch works as is for get. It is the post I've had a stub on. Currently, my solution is putting everything in FormData() - and that somehow makes it all work.

Code:
    let form = new FormData();

    let csrfs = document.querySelectorAll('input[name=csrf_token]');
    form.append(csrfs[0].name, csrfs[0].value);

    let pkg = JSON.stringify({
        view: "modules/cartproducts",
        products: productIds
    });
    form.append('json', pkg);

    fetch(SITE_CONSTANT+'/front/fetchProducts', {
        method: "post",
        body: form
    })
        .then(response => response.json())
        .then(data => {
            csrfs.forEach(e => e.value = data.csrf_token);
            if(data.products) {
                document.querySelector('.products').innerHTML = data.products;
                document.dispatchEvent(new CustomEvent('productsFetched'));
            }
        });
You can see things I made with codeigniter here: itart.pro its not overly impressive as I have very little time to learn.
Reply


Messages In This Thread
CSRF with fetch API - by Leo - 07-01-2020, 11:04 AM
RE: CSRF with fetch API - by MGatner - 07-07-2020, 10:26 AM
RE: CSRF with fetch API - by Leo - 07-07-2020, 12:51 PM
RE: CSRF with fetch API - by MGatner - 07-07-2020, 04:20 PM
RE: CSRF with fetch API - by Leo - 07-08-2020, 08:41 AM
RE: CSRF with fetch API - by InsiteFX - 07-08-2020, 11:40 AM



Theme © iAndrew 2016 - Forum software by © MyBB