Cors issue with third party api - javascript

I am struggle with getting data from third party api on browser. 'https://www.coinexchange.io/api/v1/getmarkets'
I set mode:'no-cors' as option because it seems the response header does not include Access-Control-Allow-Origin. But mode: no-cors does not allow me to access to the data.
function callApi({ url }) {
return fetch(url, {
mode: 'no-cors'
})
.then(response => {
if (!response) {
}
return response.json()
})
.then(response => {
const camelizedJson = camelizeKeys(response)
return Object.assign({},
normalize(camelizedJson),
)
})
}
The response returns type: opaque like this image and response headers is this
I believe mode: no-cors works like sending GET request from HTML img tag so I can not use the information.
Is there any way to access to the third party API whose response header does not have Access-Control-Allow-Origin? How am I supposed to call third party public api?
If you have any ideas to fix this problem, please let me know! Thank you

Related

Problem using fetch to retrive data from an API - works in Postman

I am trying to access an API using JavaScript. When accessing it using Postman everything works fine. I can make a GET request and it sends back the correct data. However when I try to do the same using fetch(), it either returns nothing or gives me an error (depending on the mode I am using).
<script>
async function get_page() {
const response = await fetch("MY_LINK", {
method:'GET',
mode:'cors',
redirect:'follow'
});
return response;
}
get_page().then(data => console.log(data)).catch(err => console.log(err));
</script>
The above throws:
Access to fetch at 'MY_LINK' from origin 'null' has been blocked by
CORS policy: 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.
If I change the mode to no-cors, I get a reply but cannot seem to find the returned message (the body attribute is null) in it, that I am seeing when I use Postman.
In a browser, with your function, this worked:
get_page().then(response => response.json()).then(data => console.log(data)).catch(err => console.log(err));
Full code (poke api :)
async function get_page() {
const response = await fetch('https://pokeapi.co/api/v2/pokemon/ditto', {
method:'GET',
mode:'cors',
redirect:'follow'
});
return response;
}
get_page().then(response => response.json()).then(data => console.log(data)).catch(err => console.log(err));
Note about CORS:
Tested on the browser console while visiting:
https://pokeapi.co/ -> ok
https://developer.mozilla.org -> FAIL (Content Security Policy)
https://www.google.com/ -> ok
so it pays to see your server code as well
This is the result of my code:

Solving error "Request header field <name> is not allowed by Access-Control-Allow-Headers in preflight response" without access to server [duplicate]

This question already has answers here:
No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API
(26 answers)
Closed 2 years ago.
I'm trying to make a GET request to the url "https://public-api.wordpress.com/wpcom/v2/work-with-us" with special header 'X-future' and value 'automattician'. However, I get the error that this header is not allowed in preflight response:
"Request header field x-future is not allowed by Access-Control-Allow-Headers in preflight response."
From searching around, it seems that this is a CORS issue and I have to add the header from the server side. However, I don't have access to the server.
Is this problem not solvable or am I missing something? Here's what I wrote in code pen to test:
let url = 'https://public-api.wordpress.com/wpcom/v2/work-with-us';
const options = {
method: 'GET', //default
headers: {'X-future': 'automattician'}
};
fetch(url, options)
.then(blob => blob.json())
.then(data => console.log(data));
You can get around these cors issues by running the fetch on your own server or serverless function.
Running this in a node script will work and allow you to pass the results back to your website.
const fetch = require("node-fetch");
function fetchServer() {
return fetch("https://public-api.wordpress.com/wpcom/v2/work-with-us", {
headers: { "X-future": "automattician" }
})
.then(res => res.json())
.then(res => res);
}
You can easily deploy this using a serverless function, sometimes called lambda in AWS but most cloud providers have something similar https://aws.amazon.com/lambda/

Download Image using Fetch API

I know this question is answered, but I am facing issue while downloading image using Fetch API. Code that I am using to get image.
function downloadImage() {
fetch('https://upload.wikimedia.org/wikipedia/commons/9/98/Pet_dog_fetching_sticks_in_Wales-3April2010.jpg',
{mode: 'no-cors'})
.then(response => response.blob())
.then(blob => {
console.log(blob);
});
}
Here, when I do console.log I get response Blob {size: 0, type: ""}.
Please let me know what I am doing wrong here?
By default fetch uses CORS mode. But when server response doesn't contain 'Access-Control-Allow-Origin' header. It skips response body.
Ironically, you have to set mode as 'no-cors'
to request opaque resources. Opaque responses can't be accessed with JavaScript but the response can still be served or cached by a service worker.
https://developers.google.com/web/ilt/pwa/working-with-the-fetch-api

Resolving CORS issue in Angular (without access to API)?

I have the following problem:
In my Angular 4 App I want to get (GET Request) data from a public API.
Just calling the URL from Browser or via Postman works perfectly but when I make an HTTP Get request from Angular I get that error:
XMLHttpRequest cannot load https://api.kraken.com/0/public/AssetPairs.
No 'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'localhost:4200' is therefore not allowed
access.
I found solutions for that but none of them resolved my issue as it is a third party API and not under my control...
I also tried setting headers but it didn't work:
let headers = new Headers({ 'Access-Control-Allow-Origin': 'true' , 'Content-Type':'application/json', 'crossDomain':'true'});
let options = new RequestOptions({ headers: headers, withCredentials: false});
return this.http.get('https://api.kraken.com/0/public/AssetPairs' , options)
.map(
(response: Response) => {
console.log(response);
const markets = response.json();
return markets;
},
(error: Error) => {
console.log('error');
console.log(error);
}
);
Thanks in advance for advice!
I suggest you to use proxy-server. You can access your third part resources though proxy server. For instance you put nginx server and add cors configuration in the nginx.conf. Angular request direct to nginx which then reroute to your third part resources.

fetch error No 'Access-Control-Allow-Origin' header is present on the requested resource

I'm using fetch API to get data from other APIs this is my code:
var result = fetch(ip, {
method: 'get',
}).then(response => response.json())
.then(data => {
country = data.country_name;
let lat = data.latitude;
let lon = data.longitude;
//fetch weather api with the user country
return fetch(`https://api.darksky.net/forecast/efc76f378da9a5bd8bb366a91ec6f550/${lat},${lon}`);
})
.then(response => response.json())
.then(data => {
// access the data of the weather api
console.log(JSON.stringify(data))
})
.catch(error => console.log('Request failed', error));
but I face error in console:
Fetch API cannot load https://api.darksky.net/forecast/efc76f378da9a5bd8bb366a91ec6f550/52.3824,4.8995. 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 set headers for the second fetch:
return fetch(`https://api.darksky.net/forecast/efc76f378da9a5bd8bb366a91ec6f550/${lat},${lon}`, {
mode: 'no-cors',
header: {
'Access-Control-Allow-Origin':'*',
}
});
error will gone but console.log(JSON.stringify(data)) do not log anything in console and the fetch not return any value.
what is the problem with my code?
The problem is not in your JavaScript code, it is in the API, the server doesn't support cross origin request, if you are the owner of this API you have to add 'Access-Control-Allow-Origin' header to the response with the allowed origins (* to allow from any origin).
in some cases jsonp request may work.
Note: this problem happen only when the request is generated from the browser
The issue will not present when "no-cors" argument is used after the url
fetch(url, {mode: "no-cors"})

Categories