Javascript Fetch vs. Ajax?

Jump to solution
DanielLim
Community Explorer

For some reason I can make requests to the GraphQL API using Ajax, but not with Fetch.

Here is the working Ajax code:

query = 'query { course(id:"1069") {name}}';
variables = { "cid": course_id };

$.ajax({
    url: '/api/graphql',
    type: 'POST',
    data: {
        query: query,
        variables: variables
    },
    success: function(result, status, xhr) {
        console.log(result);
    }
})

Here's my code using Fetch:

response = await fetch('/api/graphql', {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
        query: query,
        variables: variables
    })
});

data = await response.json();

if (response.ok) {
    console.log(data);
}

This generates a 422 status code and I can't figure out why. Can anyone help?

Labels (4)
0 Likes
1 Solution
matthew_buckett
Community Contributor

Hiya @DanielLim 

I'm assuming you're attempting to run this code in Canvas and are looking to add some custom JS to the Canvas theme?

If so the reason it works for when using the jQuery `$.ajax()` is that Canvas adds "magic" to the standard jQuery API to automatically handle the adding of the Cross Site Request Forgery token (CSRF). If you look in Chrome you Network tab you will see that the jQuery call sends a 'X-Csrf-Token' header whereas the `fetch` call doesn't have this header automatically appended.

You can work out what value should be sent by looking in the current cookies the browser has for the `_csrf_token` named cookie, then adding the header to your fetch call.

The graphql endpoint accepts JSON so although you're sending form data in one request and JSON I don't think that should cause problems.

All the best.

Matthew

View solution in original post

0 Likes