Javascript fetch vs. Smartsheet

I am trying to query a smartsheet using very vanilla Javascript, see below. I verify that cURL will work using my API key, but the code below generates 403. I cannot use "require('smartsheet');" as the website platform does not permit.

How can I get my Javascript snippet to behave as well as cURL?

const apiUrl = 'https://api.smartsheet.com/2.0/sheets';
const outputElement = document.getElementById('output');

function the_api() {
fetch(apiUrl, {
method: "GET",
mode: "no-cors",
headers: {
"Authorization": "Bearer <api key here>",
'Content-Type':'application/json',
},
})
.then(response => {
if (!response.ok) {
console.log(response);
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
// Display data in an HTML element
outputElement.textContent = JSON.stringify(data, null, 2);
})
.catch(error => {
console.error('Error:', error);
});
}

Answers

  • Brian_Richardson
    Brian_Richardson Overachievers Alumni

    no-cors is your issue…with that enabled you cannot do custom Authorization headers.

    BRIAN RICHARDSON | PMO TOOLS AND RESOURCES | HE|HIM

    SEATTLE WA, USA

    IRON MOUNTAIN

  • Thank you, Brian, this makes sense.

    Trying to fix this, the response with mode: "cors" is:

    Access to fetch at 'https://api.smartsheet.com/2.0/sheets' from origin 'https://research-dev.uoregon.edu' 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.

    So I need to do some more investigation, in particular about this "preflight" thing. The server is not permitting access from my website, though I'm still thinking there must be a way since it does work with cURL.

  • Brian_Richardson
    Brian_Richardson Overachievers Alumni
    edited 06/11/24

    Try adding the access-control-allow-origin header. It must be something with whatever is hosting your code, I don’t have this issue either using Bridge to call Smartsheet API or from Postman.

    BRIAN RICHARDSON | PMO TOOLS AND RESOURCES | HE|HIM

    SEATTLE WA, USA

    IRON MOUNTAIN