How to get XML response from API using JavaScript? - javascript

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

Related

fetch won't let me authorize get request

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.

Using SpreadShirt REST API with JavaScript / Fetch

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

Getting 401 Error code while using fetch() with a custom header

===
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

Retrieve LinkedIn access token

I'm trying to get linkedIn oauth2 access token but I stuck on making last request to https://www.linkedin.com/oauth/v2/accessToken
const body = new URLSearchParams([
['grant_type', 'authorization_code'],
['code', code],
['redirect_uri', 'http://localhost:3000/'],
['client_id', CLIENT_ID],
['client_secret', CLIENT_SECRET]
]);
const headers = new Headers({'Content-Type': 'x-www-form-urlencoded'});
window.fetch('https://www.linkedin.com/oauth/v2/accessToken', method: 'POST',body, headers)
.then(response => response.json())
.then(data => {
// rest of code
})
LinkedIn returns
Fetch API cannot load https: //www.linkedin.com/oauth/v2/accessToken. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http: //localhost:3000' is therefore not allowed access. The response had HTTP status code 404. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
so I tried to make request in 'no-cors' mode. I've got 200 but I can't get body of response,status is 0, body is null and response.json() throws SyntaxError: Unexpected end of input.
For anyone who came across this problem. We solved it by passing data from LinkedIn (code) to our backend. Backend have no need to send any preflight OPTIONS requests and can get access token without problem.
I found out your issue,
The Content-Type header value is not correct.
It's meant to be
const headers = new Headers({'Content-Type': 'application/x-www-form-urlencoded'});
NOT
const headers = new Headers({'Content-Type': 'x-www-form-urlencoded'});
DOCS: https://developer.linkedin.com/docs/oauth2 (Step 3)

ReactJS: How to parse response of files sent from REST API and display them?

Using ReactJS, I have a GET request working with fetch method, and the REST API responds with a few files. How would they be sent to me?
Meaning, can it be parsed with response.json(), so that it can be displayed as actual files from REST API and also be downloaded to local drive?
Here is the method that makes the GET request:
sendFileRequest() {
...
return dispatch => {
dispatch({
type: 'FETCH_API'
});
return fetch('http://11.22.33.44:8080/receive/files', getRequest)
.then(response => response.json()) //Could I do .json() with files being the response?
.then(APIfiles => {
//How can I parse the files returned and display them for download to local drive?
})
}
fetch({}).then(res => res.json()) or fetch({}).then(res => res.text()), it depend on the content-type of your response.
if your contentType is application/json, you should use res.json(),
if your contentType is text/plain, you should use res.text().
you can check the doc here.
Since your server just return a file, I think you should use res.text().
You need to check the likely response content-type with the one who is responsible for developing the API.
What you need to know is that REST is not fastened to JSON. It is all about resources, therefore, you may receive XML, plain text, files, etc.

Categories

Resources