Javascript API Development - CORS issue?

Jump to solution
DanielLim
Community Explorer

I am waiting to get access from Canvas to modify the Javascript (and CSS) files in the Theme Editor. In the meantime I am trying to work with the API (both REST and GraphQL) to develop some local webpages with Javascript code to report Canvas data. Here is code that worked with the https://countries.trevorblades.com/ GraphQL API but fails to work with our institution's Canvas TEST instance (I did not include the access token information below):

fetch('https://***.test.instructure.com/api/graphql', {
    method: 'POST',
    body: JSON.stringify({query : `***`}),
    headers: {
        'Content-Type': 'application/json'
    }
})
.then(res => res.json())
.then(res => console.log(res.data))
.catch(err => console.error(err))

I get the following error message:

Access to fetch at 'https://***.test.instructure.com/api/graphql' from origin 'null' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

I am unfamiliar with CORS but I take it that this error is a good thing. We don't want Canvas to provide data to requests coming from outside its domain (***.test.instructure.com). @jerry_nguyen has a great Javascript example of accessing the GraphQL API here: https://community.canvaslms.com/t5/Canvas-Developers-Group/Custom-JS-to-display-full-sortable-To-Do-.... But this code is run remotely on the Canvas domain. The problem is that I don't seem to have a good way of locally developing and testing HTML / Javascript code that accesses the Canvas API.

Am I missing something obvious? Any advice on what I can do?

Labels (2)
0 Likes
1 Solution
DanielLim
Community Explorer
Author

@matthew_buckett mentioned developing a proxy server here: https://community.canvaslms.com/t5/Canvas-Developers-Group/API-CORS-policy-No-Access-Control-Allow-O... so I ended up writing a very simple Python Flask server that enables CORS and now I can locally develop frontend Javascript webpages that make Canvas API requests (REST and GraphQL).

View solution in original post