What i try to do
I have a small ReactJS application. In this application, i try to do an REST request to the API of SpreadShirt via the JS Fetch API.
What fails
Basically i get no data. The console of the browser shows the following output:
Access to fetch at 'https://api.spreadshirt.net/api/v1/shops/100749149/sellables?mediaType=json' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
My Code
getData() {
const header = new Headers({
"Authorization": "SprdAuth apiKey=\"XXXXXXXXX"",
"User-Agent": "MukoSoft/1.0 (https://mydomain.de; my#mail.de)"
});
const options = {
method: 'GET',
headers: header
};
fetch('https://api.spreadshirt.net/api/v1/shops/100749149/sellables?mediaType=json', options)
.then(response => response.json())
.then(data => this.setState({ data: data }))
.then(() => this.setState({ loading: false }))
}
Does anyone has a hint for me, while i can't fetch via JavaScript? And can somebody explain, why the request via Postman works, but not via fetch API?
Since this is my first question on stack overflow, you can give me advices on how to formulate questions better
Related
I'm trying to extract the Workable api and display all the jobs listings into an external site.
The api documentation is here: https://workable.readme.io/reference/generate-an-access-token.
It says on the notes here:
Workable does not support Cross-Origin Resource Sharing (CORS)`
And when I try to fetch it says Access-Control-Allow-Origin header is present on the requested resource. How do I enable it? Because the Integrations settings under workable only allows me to only generate access token.
This is a sample code here when you go to this jobs documentation:
Note: I'm only using JavaScript
const options = {
method: 'GET',
headers: {accept: 'application/json', Authorization: 'Bearer AccessTokenHere'}
};
fetch('https://subdomain.workable.com/spi/v3/jobs?limit=50', options)
.then(response => response.json())
.then(response => console.log(response))
.catch(err => console.error(err));
GetResponse Api integration Using Fetch API method not working
The following SMS is showing in the console:
Cross-Origin Request Blocked:
The Same Origin Policy disallows reading the remote resource at https://api.getresponse.com/v3/contacts.
(Reason: CORS header 'Access-Control-Allow-Origin' missing).
Code is given bellow:
// main.js
// POST request using fetch()
fetch("https://api.getresponse.com/v3/contacts", {
// Adding method type
method: "POST",
// Adding body or contents to send
body: JSON.stringify(
{
campaign : {
campaignId: "5D8Qm"
},
name: "xyz",
email: "fdfdfd#gmail.com"
}
),
// Adding headers to the request
headers: {
"X-Auth-Token": "api-key o9q5s264jbp9dws0nsevnagqdst81esh",
"Content-type": "application/json"
}
})
// Converting to JSON
.then(response => response.json())
// Displaying results to console
.then(json => console.log(json));
It's a classic CORS issue as azbarcea said.
As for your comment about why cURL works but Fetch API not, you can refer to this answer in Stack Overflow.
I created a Formik login form and call to react js fetch method. Add cors in web api end and successfully run in Postman and jquery. How to call "token_type": "bearer", through react js? cors is also enabled in web api and also generate Token successfully. How to call this url https://localhost:44323/token through react js?
My code is
onSubmit={(values) => {
fetch('https://localhost:44323/token', {
method: 'POST',
header: { 'Content-type': 'application/json,multipart/form-data' },
data: JSON.stringify(values)
})
.then(r => r.json())
.then(res => {
console.log(res)
});
}}>
Error messages
The root cause of the problem can be found in the following error message shown:
"Access to fetch at https://localhost:44323/token from origin http://localhost:3000 has been blocked by CORS policy. No Access-Control-Allow-Origin header is present on the requested resource ...."
How to fix the problem?
The problem can be fixed in these ways:
1. Allow the origin (http://localhost:3000) on the server (Recommended)
This can be done by adding the following header to HTTP response on the server side:
Access-Control-Allow-Origin: http://localhost:3000
2. Send Fetch request in the 'no-cors' mode
This can be done by updating the fetch request as follows:
fetch( 'https://localhost:44323/token',
{
method: 'POST',
mode: 'no-cors',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
}
)
.then(response => {
// Code for processing the response
}
)
.catch((error) => {
// Code for handling the error
}
)
More information:
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
===
I've built a custom API with AWS API Gateway.
For one of the method, I've enable the authorization to be checked using a Lambda function.
In order to make it work, I have to add the following key: Key: authorizationToken Value: allow.
I've tested it using Postman and it's working fine, my POST is processed and I receive a response.
I'm just starting with Javascript so I've used the code provided in Postman.
Here it is:
function getData(event){
var myHeaders = new Headers();
myHeaders.set("authorizationToken", "allow");
var requestOptions = {
method: 'POST',
mode: 'no-cors'
};
fetch("https://[THE_URL_OF_MY_API]/prod/counter", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
}
And i'm getting the following error message in the console.
script.js:49 POST https://[THE_URL_OF_MY_API]/prod/counter
net::ERR_ABORTED 401 (Unauthorized)
getData # script.js:49
I've looked into the logs of the API Gateway in AWS in order to troubleshoot it:
But I can't see any logs so it seems my fetch is being block before
it's even being sent.
I checked the headers of the successful API call sent by Postman and I can't find any header apart from mine and the one generated by the application automatically.
What am I doing wrong ?
Note: I'm using similar code to another endpoint where the authorization is not enabled and it's working fine. SO I guess my header is not correctly set.
Thanks !
#CRice, Salmin Skenderovic, Jaromanda X : Thanks a lot for your feedback.
The missing myHeaders was a typo, I fixed it.
Seeing the comment about the 'no-cors', I've looked into it, enable CORS, authorized my specific header in Access-Control-Allow-Headers.
And now it's working fine.
My amended code:
var myHeaders = new Headers();
myHeaders.set("authorizationToken", "allow");
var requestOptions = {
method: 'POST',
redirect: 'follow',
headers : myHeaders
};
fetch("https://[URL_OF_MY_API_ENDPOINT]/prod/counter", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
Configuration of my API Gateway:
Configuration of my API Gateway
I am trying to get Petrol Prices from Global Petrol Prices, their API has XML as response. This is code to get XML Response.
var apiURL =
'https://www.globalpetrolprices.com/api/getGasXML_weekly.php?gasoline_diesel=2&rate=USD&countries=52&p=765982d8f9f5f25d4dafc14aa38922f2';
fetch(apiURL, {
method: 'GET',
mode: 'no-cors'
})
.then(response => response.text())
.then(str => new window.DOMParser().parseFromString(str, 'text/xml'))
.then(data => console.log(data));
But I am not getting any response from the code. However, when I visit to that URL I get XML response like this.
<mtc:data><mtc:country id="DZ" country_name="Algeria">
<mtc:gas_type id="diesel">0.2</mtc:gas_type>
<mtc:year>2018</mtc:year>
<mtc:week>34</mtc:week>
<mtc:week_start>20-08-2018</mtc:week_start>
<mtc:currency>USD</mtc:currency></mtc:country>
</mtc:data>
Can anyone help me with this? TIA
If you send a request with JavaScript on the client side, you get an error. No 'Access-Control-Allow-Origin' header is present on the requested resource. you will get the error
You have to do by Server side