Fetch XML weather data from yr.no - javascript

Im not an experienced with XML but trying to create a website and need to use some weather data from a norwegian weather services (yr.no) specific this url(https://www.yr.no/sted/Norge/Akershus/B%C3%A6rum/Kols%C3%A5s/varsel.xml)
I have tried using this code under, but having a problem having a problem.. where can i go from here?
fetch('https://www.yr.no/sted/Norge/Akershus/Bærum/Kolsås/varsel.xml', {
mode: 'no-cors'
})
.then(function(resp) {
return resp.text();
})
.then(function(data) {
let parser = new DOMParser(),
xmlDOc = parser.parseFromString(data, '/sted/Norge/Akershus/Bærum/Kolsås/varsel.xml'
);
console.log(xmlDOc);
});

mode: 'no-cors' means "I am not doing anything that needs CORS permission, don't ask for it".
resp.text(); requires CORS permission when dealing with cross-origin requests.
So don't say mode: 'no-cors'.
(If the URL does not come with CORS permission, then you'll need to look at changing that or using a proxy. Further reading: XMLHttpRequest cannot load XXX No 'Access-Control-Allow-Origin' header)

Related

Javascript fetch API returning opaque response [duplicate]

I tried to use this Cat Facts API like so:
const URL = "https://catfact.ninja/fact?limit=1" // In browser, this displays the JSON
fetch(URL).then(response=> {
console.log(response);
return response.json();
}
);
but I got
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://catfact.ninja/fact?limit=1. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
TypeError: NetworkError when attempting to fetch resource.
so after trying with
fetch(URL, {mode:'no-cors'})
.then(response=> {
console.log(response);
return response.json();
}
);
I now get
Response { type: "opaque", url: "", redirected: false, status: 0, ok: false, statusText: "", headers: Headers, body: null, bodyUsed: false }
SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data
I understand from here that I won't be able to use this API as intended. But if so, what is the purpose of it and how is it intended to be used (this info does not account for the issue)?
An opaque response is one you cannot see the content of. They aren't useful in of themselves.
Setting mode: 'no-cors' is a declaration that you don't need to read the response (or do anything else that requires CORS permission).
For example, the JavaScript might be sending analytics data to be recorded by a server.
The benefit of no-cors mode is that it lets you send the data without getting exceptions reported in the JS console (which would (a) look bad if anyone opened it and (b) flood the console with junk that makes it hard to find real errors).
If you need to access the response, don't set mode: 'no-cors'. If it is a cross origin request then you will need to use some other technique to bypass the Same Origin Policy.
Aside: "Access-Control-Allow-Origin": "*" is a response header. Do not put it on a request. It will do nothing useful and might turn a simple request into a preflighted request.
Adding {mode: 'no-cors'} is not a catch-all for CORS errors. You might be better off using a CORS Proxy.
This question might also be of use to you.
Alternatively, and depending on your needs, using a different API could be the easiest solution. I was able to return a cat fact from "https://meowfacts.herokuapp.com/". See below.
const URL = "https://meowfacts.herokuapp.com/"
async function getCatFact() {
const response = await fetch(URL)
console.log(await response.json())
}
getCatFact()

i am using window.fetch for downloading file , but is generating error file on server not on local

function download(id) {
$.get(base_url + "account/download/" + id, function (data) {
var data = JSON.parse(data);
if (data.code == 1) {
console.log(data)
//data.filePath = "https://s3.amazonaws.com/stores-products/8c0123ef4a1d685bbf50582ffb461573.jpg"
fetch(data.filePath, { mode: 'no-cors', method: 'GET' })
.then(resp => resp.blob())
.then(blob => {
console.log(blob)
const url = window.URL.createObjectURL(blob);
console.log(url)
const a = document.createElement('a');
//a.style.display = 'none';
a.href = url;
a.download = data.fileName;
document.body.appendChild(a);
a.click();
a.remove();
window.URL.revokeObjectURL(url);
})
.catch(() => bootbox.alert("Unable to Download File"));
}
else if (data.code == 0) {
bootbox.alert(data.msg);
}
});
}
under get api call I am using fetch with url of amazon s3 , its working fine on local but it generating error file on server , please review my code and let me know the issue in this code. I did not getting any error message , but downloaded file , when I am opening it show error to load file.
In order to be able to fetch resources cross-origin you need to understand and properly configure CORS headers, i.e. the server needs to send the right Access-Control-Allow-Origin and Access-Control-Allow-Methods.
Otherwise browser security will prohibit the request.
Trying to circumvent this with {mode: 'no-cors'} does not work as one might expect: although 'no-cors' will ignore the CORS headers of the server the response content will then be inaccessible to your javascript code, see the documentation for Request.mode:
no-cors — Prevents the method from being anything other than HEAD, GET or POST, and the headers from being anything other than simple headers. If any ServiceWorkers intercept these requests, they may not add or override any headers except for those that are simple headers. In addition, JavaScript may not access any properties of the resulting Response. This ensures that ServiceWorkers do not affect the semantics of the Web and prevents security and privacy issues arising from leaking data across domains.
This is due to the resulting Response's type being opaque preventing you from accessing its actual contents.
For further explanation see this excellent answer to a similar question.
So what you need to do is to use {mode: 'cors'} and have the server appropriately configured to allow for cross-origin requests from your frontend domain.

Need a way to enable CORS in vueJS [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 am new to vueJS and version using is 2.0. I need to fetch some JSON data from url. Using javacsript fetch methods to get the data from URL. below is my code,
function getValue() {
const requestOptions = {
method: "GET",
header: {"Access-Control-Allow-Origin": "GET"}
};
fetch("http://api.plos.org/search?q=title:DNA", requestOptions)
.then(
(response) => {
console.log(response.json());
}
);
}
getValue();
I am getting CORS issue like,
Access to fetch at 'http://api.plos.org/search?q=title:DNA' from origin 'http://localhost:8080' 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.
I tried all the possibilities which available in stack-overflow. But no luck.
Any help would be much appreciated.
JSFiddle link - https://jsfiddle.net/m45hsekf/
Did you tried to set the mode to no-cors like the error suggests to you?
set the request's mode to 'no-cors' to fetch the resource with CORS
disabled.
I have tested it and it works:
const requestOptions = {
method: "GET",
mode: "no-cors"
};
So the request looks like this:
fetch("http://api.plos.org/search?q=title:DNA", {
mode: "no-cors"
})
.then(response => response.json())
.then(result => {
console.log(result);
});
CORS should be enabled at server level like node or java application.
Access-Control-Allow-Origin : "test-client.com" or use "*"(not recommended). Then allow this value at the server
Get is your http method not the origin value
To enable in node use this line
res. header("Access-Control-Allow-Origin", "*"); // again * is not a best practice. Please accept this as answer too
Refer to the url below for more info
https://dzone.com/articles/cors-in-node
when i have problems while i develop, i use crhome extension called CORS UNBLOCK, then i can test my api, and when i deploy to final server, always is in the same domain then i havent cors ploblem

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.

Categories