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
- 63.7K Get Help
- 405 Global Discussions
- 215 Industry Talk
- 456 Announcements
- 4.7K Ideas & Feature Requests
- 141 Brandfolder
- 136 Just for fun
- 57 Community Job Board
- 459 Show & Tell
- 31 Member Spotlight
- 1 SmartStories
- 297 Events
- 37 Webinars
- 7.3K Forum Archives