I'm trying to use fetch over the broswer but it just won't work.
I tried:
fetch('https://api-2sizcg3ipa-uc.a.run.app/fats', {
headers: {'Authorization': 'Basic ' + btoa('username:password')},
mode:'no-cors'
})
.then(response => response.json())
.then(json => console.log(json));
But it gives me two errors:
GET https://api-2sizcg3ipa-uc.a.run.app/fats net::ERR_ABORTED 403
Uncaught (in promise) SyntaxError: Unexpected end of input
at fetch.js:5
What am I doing wrong? I works when I do it with curl.
You said:
mode:'no-cors'
This makes fetch quietly ignore anything that requires permission via CORS instead of failing with an error.
Sending Authorization headers requires permission via CORS.
So don't say you don't want to use it.
Do, however, say credentials: 'include' as you want to send credentials.
Related
i try to fetch elastic api using javascript with basic authentication, but there is error show that request header field authorization is not allowed by acccess-control-allow-headers, is it something wrong with the elasticsearch api or the wrong is on my code? i already setting enable cors on elastic, i tried curl to get elastic data with auth and it works, does the fetch code is wrong?
the console error :
the fetch code :
fetch('http://192.168.150.220:9900/', {method:'GET',
headers: {'Authorization': 'Basic ' + btoa('em_user:3md#t#2o22')}})
.then(response => response.json())
.then(json => console.log(json));
To use fetch from your browser, you will have to allow cross-origin requests in the ElasticSearch configuration:
http.cors.enabled : true
http.cors.allow-origin: "*"
http.cors.allow-methods: OPTIONS, HEAD, GET, POST, PUT, DELETE
http.cors.allow-headers: X-Requested-With,X-Auth-Token,Content-Type,Content-Length,Authorization
http.cors.allow-credentials: true
Source:
https://www.elastic.co/guide/en/elasticsearch/reference/8.2/modules-network.html
https://www.elastic.co/guide/en/cloud-enterprise/current/ece-configure-cors.html
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
===
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'm trying to send the following request in my react application
curl -H 'Client-ID: p0gch4mp101fy451do9uod1s1x9i4a' \
-X GET 'https://api.twitch.tv/helix/streams?game_id=33214'
I am able to put this exact string into my terminal and receive a response, but how exactly do I go about doing this in JavaScript or REACT?
I have tried using fetch in react but that only allows me to send a get request and that gives me an response of unauthorized access because it only takes a link, and if I send the entire thing as a string it'll just give me a 404 error because it's unrecognized.
In my terminal I can just paste in the whole string and get a valid response back. how do I replicate this in JavaScript or react?
Fetch works with any standard request method and allows for setting headers as below:
const url = 'https://api.twitch.tv/helix/streams?game_id=33214';
const options = {
method: 'GET',
headers: {
'Client-ID': 'p0gch4mp101fy451do9uod1s1x9i4a'
},
//body: JSON.stringify({name:'test'}) //example of how to have a body also
};
fetch(url, options)
.then(res=>{
if(!res.ok)
throw new Error(res.statusText);
return res.json();
})
.then(json => console.log(json))
.catch(err => {
console.error('Request failed', err)
});
for more info read the docs https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API
or check this https://flaviocopes.com/fetch-api/
I'm developing an app with React + Redux and I have my JSON database within a Firebase DB.
To do this I'm tryin to fetch my data from a valid URL (validated from Firebase simulator)
let firebase = 'https://******.firebaseio.com/**/*/***/*'
return (dispatch) => {
return fetch(firebase)
.then(res => res.json())
.then(json => dispatch({ type: 'GET_JSON', payload: json }))
}
This returns to me the error:
Fetch API cannot load https://console.firebase.google.com/project/****/database/data/**/*/***/*. Redirect from 'https://console.firebase.google.com/project//database/data/**///' to 'https://accounts.google.com/ServiceLogin?ltmpl=firebase&osid=1&passive=true…ole.firebase.google.com/project//database/data///**/' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.`
I've tried many solutions, like adding to fetch's second argument { mode: 'no-cors', credentials: 'same-origin'}, but when I try this i get Uncaught (in promise) SyntaxError: Unexpected end of input.
What am I missing?
likely error that arise to cors blocked when using firebase is
when you initiate a put or get request with an incomplete firebase url
e.g
// wrong form
this.http.get('https://******.firebaseio.com/data') //this will throw an exception
// correct form
this.http.get('https://******.firebaseio.com/data.json')
I had this problem with a serviceworker implementation of fetch
self.addEventListener('fetch', (e) => {
fetch(e.request) // valid arg && works with firebase
fetch(e.request.url) // valid arg but will cause access-control error!
}
For a simple request to be allowed cross-domain, the server simply needs to add the Access-Control-Allow-Origin header to the response.
Also refer this turorial, if you have any doubts
Cross-Origin XMLHttpRequest
Using CORS.