Testing external API's using Angular 2 & Apache - apache

I am trying to make an HTTP requeset to an external API using the following request:
let headers = new Headers({
'X-Requested-With': 'XMLHttpRequest',
'Content-Type': 'application/x-www-form-urlencoded',
'Access-Control-Allow-Origin': "*"
});
let options = new RequestOptions({ headers: headers });
let body = JSON.stringify({
test: test
comments: "test"
});
this.http.post("EXTERNAL_API_URL", body, options)
.map(res => res.json())
.subscribe((data) => {
console.log(data);
});
When I am making the API call from Chrome Postman plugin, the API works without any problem.
When I'm trying to make this call from my angular 2 app, the call is not working and returns the following error:
XMLHttpRequest cannot load MY_API_URL. 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:4200' is therefore not allowed access.
I know that I can access bypass it using the no web-security chrome:
Chrome.exe --disable-web-security
But I wish to make it work without it...
I also tried to add Header set Access-Control-Allow-Origin "*" in my http.conf as described here.
Any ideas?

Related

get CORS problem when ty to get a token in keycloak with vuejs and axios

I trying to access one keycloak with axios in my vuejs app, but I receive the cors error, can someone help me please? (If I make a post from POSTMAN to my keycloak works fine)
I using this code:
const params = new URLSearchParams();
params.append("grant_type", "password");
params.append("client_id", "notas-front");
params.append("username", usuario.value);
params.append("password", password.value);
console.log(params);
const config = {
// withCredentials: true,
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
};
axios.defaults.headers.common["Access-Control-Allow-Origin"] =
"http://localhost:8080";
axios
.post(
"http://localhost:8082/auth/realms/lumera/protocol/openid-connect/token",
params,
config
)
.then((response) => {
console.log(response);
});
and get this error:
but when I look the request I can't find the error:
the OPTIONS returns 200
but the POST dont
Postman doesn't care about Same Origin Policy, browser do. That's why your request is working in Postman but not in the browser.
Access-Control-Allow-Origin is a response header, you can't set it on the client request. And as you can see from the OPTIONS response headers your server is returning: Access-Control-Allow-Origin: http://localhost:8080
In a development environment the best way to solve this is setting a proxy in your vue configuration. Otherwise you should configure the server to allow requests from localhost:8080
Configure Web Origins properly in the Keycloak notas-front client config.

Request header field authorization

I am trying to create "UUID" form this Api call
I am using axios and vue.js. Here's my source code.
generateUUID() {
// console.log("call generate uuid");
const headers = {
'Content-Type': 'application/json',
'Access-Control-Allow-Headers': '*',
'Access-Control-Allow-Origin': '*'
}
axios.get('https://www.uuidtools.com/api/generate/v1', {
headers: headers
}).then(response => console.log(response))
},
But unfortunately I am getting
Access to XMLHttpRequest at 'https://www.uuidtools.com/api/generate/v1' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I have tried searching google and followed many answers already to that question but got nothing.
Problem(s)
Access-Control-Allow-Headers and Access-Control-Allow-Origin are response headers, not request headers. Specifying them in a request is more than useless; it's actually counterproductive, here.
Why would you specify a content type for a GET request? GET requests are not supposed to have a body:
A payload within a GET request message has no defined semantics;
sending a payload body on a GET request might cause some existing
implementations to reject the request.
According to my tests, the resource that you're requesting (https://www.uuidtools.com/api/generate/v1) appears to be CORS-aware but expects only simple requests, not preflight requests. And because your request contains headers that are not CORS-safelisted, it gets preflighted by your browser, and the preflight access-control check fails.
Solution
Just send a simple GET request (without adding any headers):
fetch('https://www.uuidtools.com/api/generate/v1')
.then(r => r.json())
.then(arr => arr[0])
.then(console.log)
Console output
No CORS error, then:
]

Http with token in Ionic 4

(Sorry for my bad english) I have to access an api, with a token that they have provided me. My problem is that I don't know how to implement it, after searching and searching, it gives me the following error:
Access to XMLHttpRequest at 'https://www.presupuestoabierto.gob.ar/api/v1/credito' from origin 'http://localhost:8100' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
I pass my code to you, to indicate that it is wrong in the definition of the token (the x instead of the token) and eventually in the CORS policy, thank you very much!
const headers = { 'Authorization': 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': 'http://localhost:8100'}
this.http.get<any>('https://www.presupuestoabierto.gob.ar/api/v1/credito', { headers }).subscribe(data => {
this.datos = data.blabla;
})
Headers should pass like this in Ionic- Angular. Make sure that you have a service file.Visit this link to know more about services:
https://angular.io/tutorial/toh-pt4
let headers = new Headers({
'Content-Type' : 'application/json',
'Auth':authvalue
});
return this.http.get(url,options).pipe(map(res => res.json()));

Vue Resource Cross-site HTTP request

Normally, when I make a jQuery request to a non-local server, it applies Cross-site HTTP request rules and initially sends an OPTIONS request to verify the existence of an endpoint and then it sends the request, i.e.
GET to domain.tld/api/get/user/data/user_id
jQuery works fine, however I would like to use Vue Resource to deal with requests. In my network log, I see only the actual request being made (no OPTIONS request initially), and no data is being received.
Anybody has an idea how to solve this?
Sample Code:
var options = {
headers: {
'Authorization': 'Bearer xxx'
}
};
this.$http.get(config.api.base_url + 'open/cities',[options])
.then(function(response){
console.log('new request');
vm.cities = response;
}, function(error){
console.log('error in .js:');
console.log(error);
});
jquery-request
Solution:
As #Anton mentioned, it's not necessary to have both requests (environment negligible). Not sure what I have changed to make it work, but the request gave me an error. It consisted in setting the headers correctly. Headers should not be passed as options but as a property of http:
this.$http({
root: config.api.base_url + 'open/cities', // url, endpoint
method: 'GET',
headers: {
'Authorization': 'Bearer xxx'
}
}).then(function(response){
console.log('new request');
vm.cities = response;
}, function(error){
console.log('error in .js:');
console.log(error);
});
Thank you guys, it was a team effort :)
Is it a requirement that an additional OPTIONS request is being made? I have created a small (32 LOC) example which works fine and retrieves the data:
https://jsfiddle.net/ct372m7x/2/
As you can see, the data is being loaded from a non-local server. The example is located on jsfiddle.net and the request is made to httpbin.org - this leads to CORS being applied (you can see the Access-Control-Allow-Origin header in the screenshot below).
What you also see is that only the GET request has been executed, no OPTIONS before that.

mootools Request class and CORS

I'm trying to use CORS to have a script do an Ajax request to geonames.
My script calls this web service method: http://www.geonames.org/export/web-services.html#findNearby
If you check the response headers of the sample call, they include:
Access-Control-Allow-Origin: *
When I try this with mootools (version 1.4.5 just downloaded):
var urlGeonames = "http://api.geonames.org/findNearbyPlaceName";
var req = new Request({
method: 'get',
url: urlGeonames,
data: {
'lat': '89.18',
'lng': '-0.37',
'username': 'myusername',
'radius': '5'
}
}).send();
then I get an error that says :
XMLHttpRequest cannot load
http://api.geonames.org/findNearbyPlaceName?lat=89.18&lng=-0.37&username=myusername&radius=5.
Origin http://127.0.0.1 is not allowed by Access-Control-Allow-Origin.</pre>
On the other hand, when I try old style Ajax code like this:
invocation = new XMLHttpRequest();
if(invocation)
{
invocation.open('GET', urlFlickr, true);
invocation.onreadystatechange = handler;
invocation.send();
}
then it works and I get the XML response in the XHR responseXML.
I found this post A CORS POST request works from plain javascript, but why not with jQuery? that is similar. But here I'm not dealing with my server so I can only work on the javascript side.
Has anyone worked with CORS and mootools and can help on this issue ?
Thanks so much
JM
Hey man check out mootools more JSONP this will solve your problem:
http://mootools.net/docs/more/Request/Request.JSONP
Also it looks like your forgetting to ask for it in JSON format from geonames.org
Try something like:
var myJSONP = new Request.JSONP({
url: 'http://api.geonames.org/findNearbyPlaceNameJSON',
data: {
'lat': '89.18',
'lng': '-0.37',
'username': 'myusername'
},
onRequest: function(url){
// a script tag is created with a src attribute equal to url
},
onComplete: function(data){
// the request was completed.
console.log(data);
}
}).send();
Hope this helps!
The first answer on this other thread:
MooTools CORS request vs native Javascript
Might help.
Basically, the X-Requested-With header is automatically sent by the Mootools with the request, but the server either has to be configured to accept that header or you can remove it using
delete foo.headers['X-Requested-With'];
Before calling
foo.send();
To allow it by the server, you can add this to the .htaccess file of your script that gives back the JSON data:
Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Headers "Origin, X-Requested-With, Content-Type, Accept"
So yours would look like:
var myJSON = new Request({
url: 'http://api.geonames.org/findNearbyPlaceNameJSON',
data: {
'lat': '89.18',
'lng': '-0.37',
'username': 'myusername'
},
onRequest: function(url){
// a script tag is created with a src attribute equal to url
},
onComplete: function(data){
// the request was completed.
console.log(data);
}
});
delete myJSON.headers['X-Requested-With'];
myJSON.send();