I am new to JavaScript and i am trying to send api request from JavaScript.
I am getting below error while calling external endpoint from JavaScript.
from origin 'null' has been blocked by CORS policy: Request header field x-api-key is not allowed by Access-Control-Allow-Headers in preflight response.
var url = "<external_api_for_graphQl"
var api_key = "<api_key>"
var xhr = new XMLHttpRequest();
xhr.open("POST", url, false);
xhr.setRequestHeader("x-api-key", api_key);
xhr.send("");
alert(xhr.status);
any idea how we can resolve this?
Thanks
try to set header
xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
xhr.setRequestHeader("Access-Control-Allow-Credentials", "true");
xhr.setRequestHeader("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
xhr.setRequestHeader("Access-Control-Allow-Headers", "Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers");
The Access-Control-Allow-Headers header is sent by the server to let the client know which headers it supports for CORS requests. The value of Access-Control-Allow-Headers should be a comma-delineated list of header names, such as "X-Custom-Information" or any of the standard but non-basic header names (which are always allowed).
This error occurs when attempting to preflight a header that is not expressly allowed (that is, it's not included in the list specified by the Access-Control-Allow-Headers header sent by the server). To fix this, the server needs to be updated so that it allows the indicated header, or you need to avoid using that header.
one think you can try is this:
$.ajax({
headers: { "Accept": "application/json", "x-api-key":"<x-api-key>"},
type: 'POST',
url: '<external_api_for_graphQl>',
crossDomain: true,
beforeSend: function(xhr){
xhr.withCredentials = true;
},
success: function(data, textStatus, request){
console.log(data);
}
});
Related
I'm trying to make an rest api request to realla https://realla.co/api/#/ from localhost, I have an api key and can make the request via PHP but having issues using ajax:
var URL = "https://realla.co/api/v1/listings/search";
var usr = 'api';
var psw = 'hidden';
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json",
url: URL,
crossDomain: true,
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", "Basic " + btoa(usr + ":" + psw))
},
success: function(result) {
console.log('success');
},
error: function(req, status, err) {
console.log('Something went wrong', status, err);
}
});
Returns the error
XMLHttpRequest cannot load https://realla.co/api/v1/listings/search. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://dw.dev' is therefore not allowed access. The response had HTTP status code 403.
I tried to fix that problem with https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en but still get the same message.
I've added the following function (running Wordpress):
/*
* Modify HTTP header
*/
function new_headers($headers) {
if (!is_admin()) {
$headers['Access-Control-Allow-Origin'] = '*';
$headers['Access-Control-Allow-Methods'] = 'GET, POST, PATCH, PUT, DELETE, OPTIONS';
$headers['Access-Control-Allow-Headers'] = 'Origin, Content-Type, X-Auth-Token';
}
return $headers;
}
add_filter('wp_headers', 'new_headers');
I've tried other APIs (Facebook) and that works but I wonder if I'm missing something with this.
The documentation for Realla is pretty thin, but I wonder if I'm doing something wrong.
Thanks
let's try this
it will work
Add header in requested resource file
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');
?>
Issue was realla's side. The API prevents requests being made via ajax.
In order to use the API, you are required to make requests from the server rather than the clients browser.
Sorry to waste people's time, hopefully this answer will help anyone else who feels like they're banging their head against a brick wall.
I'm trying to integrate a custom application with Keyrock Fiware Identity Manager.
The flow is the following:
The user clicks on LOGIN button
He is redirected to the
/oauth2/authorize/?response_type=code&client_id={clientid}&state=xyz&redirect_uri=http:{ip}:{port}
The user inserts his credentials
After the authentication he is redirected to my application where I try to retrieve the token as follow:
var reqData = "grant_type=authorization_code&code=" + code + "&redirect_uri=" + http:{ip}:{port};
var reqHeaders = new Object();
reqHeaders.Access-Control-Allow-Headers= "Content-Type, Access-Control-Allow-Headers,Access-Control-Allow-Origin, Authorization, X-Requested-With, origin, accept",
reqHeaders.Access-Control-Allow-Methods= "POST, GET, OPTIONS, DELETE, PUT",
reqHeaders.Access-Control-Allow-Origin="*"
reqHeaders.Access-Control-Expose-Headers="http://*/*"
reqHeaders.Authorization="Basic {token}"
reqHeaders.Content-Type="application/x-www-form-urlencoded"
reqHeaders.X-Requested-With="XMLHttpRequest"
$.ajax({
url : idmURL + '/oauth2/token',
type : 'POST',
dataType : 'json',
crossDomain : true,
data : reqData,
headers : reqHeaders,
success : function(data) {
console.log(data);
token = data.access_token;
}
});
But the post request never starts because I receive:
XMLHttpRequest cannot load http://{ip}:{port}/oauth2/token. Request header field Access-Control-Allow-Methods is not allowed by Access-Control-Allow-Headers in preflight response.
I've tried to insert the {ip}:{port} to the CORS_WHITELIST and to the ALLOWED_HOST in the local_settings.py file of Keyrock, but nothing changes.
Anyone can help me?
Ironically, I think the issue is caused by the fact that you're using the CORS headers meant for responses in your request:
Access-Control-Allow-Headers
Access-Control-Allow-Methods
Access-Control-Allow-Origin
Access-Control-Expose-Headers
Thus the preflight fails because the server does not allow these, only a subset of headers as provided in the response header Access-Control-Allow-Headers.
Remove these from the request.
For more info: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
Hy, when I try to access the Microsoft Cognitive Services API via JavaScript from my server/local machine I get the following error.
XMLHttpRequest cannot load http://api.projectoxford.ai/vision/v1.0/analyze?visualFeatures=Categories. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://myUrl.com' is therefore not allowed access. The response had HTTP status code 401.
This is my request code:
function requestAPI(){
var params = {
// Request parameters
"visualFeatures": "Categories"
};
$.ajax({
url: "http://api.projectoxford.ai/vision/v1.0/analyze?" + $.param(params),
beforeSend: function(xhrObj){
// Request headers
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key","{myKey}");
},
type: "POST",
// Request body
data: "{'url':'http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg'}",
})
.done(function(data) {
alert("success");
})
.fail(function() {
alert("error");
});
}
In my .htaccess I already added:
Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"
When I test the request with hurl.it it works. Just from my server it doesn't.
Looks like you are setting CORS headers for your server which means someone can make cross-domain request to your server.
Microsoft Cognitive Services have to add these headers on their server so that you can make cross-domain request to them or you have to use JSONP.
I have a controller with service that would get the json from other server and i came to this
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http:somesite.com. This can be fixed by moving the resource to the same domain or enabling CORS.
I notice that some of the same issue would be fix by "Access-Control-Allow-Origin": "*" in header my in my case I don't see any progress on fixing it.
this the code for my controller :
var myApp = angular.module('cplanner',[]);
myApp.controller('GetItemCtrl', ['$scope', '$http', function($scope, $http) {
var itemUrl = 'http:somesite.com';
//console.log(itemUrl);
$http({url: itemUrl,
dataType: 'json',
method: 'POST',
dataType : 'json',
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "POST, GET, OPTIONS, PATCH, DELETE",
"Access-Control-Allow-Headers": "Origin, X-Requested-With, Content-Type, Accept"
},
xhrFields: {
withCredentials: true
}}).success(function(data, status, headers, config) {
//check if the response has ok status
if(data.status == "ok"){
console.log(data.data);
$scope.items = data.data;
}
}).error(function(data, status, headers, config) {
});
}]);
I added the header but it seem not to fix my cross origin issue. Could anyone drive me by any comments and suggestion on how am i able to get the response from another server source.
thank you in advance.
CORS is a server solution - that is - the first request a web client (JS) sends to a different domain (hence cross domain) is an OPTIONS request - which is replied by the origin server with weather or not it respect cross domain requests, if so it answers:
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "POST, GET, OPTIONS, PATCH, DELETE",
"Access-Control-Allow-Headers": "Origin, X-Requested-With, Content-Type, Accept"
Then the browser sends another request - the actual request that was meant to be sent.
This whole mechanism takes place automatically. All you have to do is enabling CORS on your server.
To enable CORS, here are some useful links:
ASP.NET WEBAPI
APACHE
CORS is something that has to be enabled on the server. If you don't have access to that server you probably won't be able to do what you were hoping. If you do have access you'll need to read up on how to enable it for whatever language the api was written in :)
See here for more info: CORS request is not allowed with AngularJS
Let's say, I have a Tornado web server (localhost) and a web page (othermachine.com), and the latter contains javascript that needs to make cross-domain ajax calls to the Tornado server.
So I set up my Tornado as such:
class BaseHandler(tornado.web.RequestHandler):
def set_default_headers(self):
self.set_header("Access-Control-Allow-Origin", "http://www.othermachine.com")
self.set_header("Access-Control-Allow-Credentials", "true")
self.set_header("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE,OPTIONS")
self.set_header("Access-Control-Allow-Headers",
"Content-Type, Depth, User-Agent, X-File-Size, X-Requested-With, X-Requested-By, If-Modified-Since, X-File-Name, Cache-Control")
And my javascript makes a jQuery call:
$.ajax({
type: 'GET',
url: "http://localhost:8899/load/space",
data: { src: "dH8b" },
success: function(resp){
console.log("ajax response: "+resp);
},
dataType: 'json',
beforeSend: function ( xhr ) {
xhr.setRequestHeader('Content-Type', 'text/plain');
xhr.setRequestHeader('Access-Control-Request-Method', 'GET');
xhr.setRequestHeader('Access-Control-Request-Headers', 'X-Requested-With');
xhr.withCredentials = true;
}
});
But I get the lovely XMLHttpRequest cannot load http://localhost:8899/load/space?src=dH8b. Origin http://www.othermachine.com is not allowed by Access-Control-Allow-Origin error. I can't tell which side of jQuery / Tornado (or both?) am I not setting up correctly.
According to dev tools, these are the headers the jQuery request is sending:
Request Headers
Accept:*/*
Origin:http://www.othermachine.com
Referer:http://www.othermachine.com/athletes.html?src=BCYQ&msgid=6xjb
User-Agent:Mozilla/5.0 ...
If I simply make a request from my browser's url field I get a '200 OK' with this:
Response Headers
Access-Control-Allow-Credentials:true
Access-Control-Allow-Headers:Content-Type, User-Agent, X-Requested-With, X-Requested-By, Cache-Control
Access-Control-Allow-Methods:GET,POST
Access-Control-Allow-Origin:http://www.othermachine.com
Content-Length:0
Content-Type:text/html; charset=UTF-8
Server:TornadoServer/2.2.1
Does that mean Tornado is doing its job? I tried to follow the advice of all the stackoverflow CORS+jQuery posts (e.g. this), to no avail. CORS in concept seems simple enough, but maybe I am fundamentally misunderstanding what is supposed to happen in a CORS transaction... please help! Thanks in advance.
Nevermind, coding too late and too long causes one to trip over things the size of typos. For the record, this is all you need for jQuery:
var data = { msgid: "dH8b" },
url = "http://localhost:8899/load" + '?' + $.param(data);
$.getJSON( url, function(resp){
console.log("ajax response: "+resp+" json="+JSON.stringify(resp));
});
And this is all you need for Tornado:
class BaseHandler(tornado.web.RequestHandler):
def set_default_headers(self):
self.set_header("Access-Control-Allow-Origin", "http://www.othermachine.com")
Using jQuery 1.7.2, Tornado 2.2.1.
try setting origin to be: othermachine.com. it should be a domain name, not a website address