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
-
no-cors is your issue…with that enabled you cannot do custom Authorization headers.
-
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.
-
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.
Categories
- All Categories
- 14 Welcome to the Community
- Smartsheet Customer Resources
- 64.1K Get Help
- 414 Global Discussions
- 221 Industry Talk
- 460 Announcements
- 4.8K Ideas & Feature Requests
- 143 Brandfolder
- 141 Just for fun
- 58 Community Job Board
- 462 Show & Tell
- 32 Member Spotlight
- 1 SmartStories
- 299 Events
- 38 Webinars
- 7.3K Forum Archives