I'm working on a phoneGap app using the file:// protocol. I keep getting this error when using ajax. I have header("Access-Control-Allow-Origin:*") on my server page. But no matter what I'm can't get an ajax response. What do I do?
Failed to load file:///C:/test4/www/trackmyrunning.byethost22.com: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.
$("#b").on('click',function(){
//pull vars
var username = $('#username').val();
var password = $('#password').val();
$.ajax({
url: "trackmyrunning.byethost22.com",
type: 'POST',
success: function(data)
{
$("#loginMessage").html(data);
},
error: function(xhr, status,error)
{
alert(xhr.status + status + error);
}
});
//request for username
/* $.get("trackmyrunning.byethost22.com/index.", {user:username,pass:password}).done(function(data){
$("#loginMessage").html(data);
}); */
});
I also have as well. I tried modifying it to and no luck. The error message I get in the alert is 0 error, basically access denied do to cross origin.
I face same issue while developing mobile app using phone gap and spring webservice.
Remember you must pass username and password credentials that is missing here
Then set headers
The Access-Control-Allow-Origin header is a response header that has to be set server side. That is, if the respective server doesn't send this header, the browser prevents you from requesting information from this server due to cross server (domain, subdomain and protocol) infringement.
It would allow requests only if the originating page was served by the same server (domain, subdomain and protocol).
Modify your js file like this ,
$("#b").on('click',function(){
//pull vars
var username = $('#username').val();
var password = $('#password').val();
$.ajax({
url: "trackmyrunning.byethost22.com",
type: 'POST',
data: { username : username , password : password } ,
headers: {
'Access-Control-Allow-Origin': '*'
},
crossDomain: true,
success: function(data)
{
$("#loginMessage").html(data);
},
error: function(xhr, status,error)
{
alert(xhr.status + status + error);
}
});
});
If problem still existing you must modify your server side code.
Following way you can set headers in java response (java back end),
try
{
res.setContentType("application/json");
res.addHeader("Access-Control-Allow-Credentials", "true");
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Methods", "*");
res.setHeader("Access-Control-Allow-Headers", "X-Requested- With,Host,User-Agent,Accept,Accept-Language,Accept-Encoding,Accept-Charset,Keep-Alive,Connection,Referer,Origin");
res.setHeader("Access-Control-Max-Age", "8080");
res.setCharacterEncoding("utf-8");
res.getWriter().write(response);
}
catch (IOException e)
{
}
Following way you can set header in php ( backend php),
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Credentials: true");
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
header('Access-Control-Max-Age: 1000');
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token , Authorization');
What you are missing is the scheme for the url, and in a Phonegap app when no scheme is provided for a url, the default one (file://) is used.
Change your url to include http:// or https:// (based on your configuration)
Example:
url: "http://trackmyrunning.byethost22.com"
Related
I am getting a CORS issue when trying to use POST with my API.
Access to XMLHttpRequest at 'http://localhost/finalMandatory/api/track/create.php' from origin 'null' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
I've tried to follow some other posts that seems to have the same issue, but I'm having a hard time implementing it in my own code.
$.ajax({
url: "http://localhost/finalMandatory/api/track/create.php",
type : "POST",
contentType : 'application/json',
data : form_data,
success : function(result) {
showProducts();
},
error: function(xhr, resp, text) {
console.log(xhr, resp, text);
console.log(form_data);
}
});
I'm also using these headers in my api, which i thought would be enough to deal with CORS problems.
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
I hope someone can help me fix my issue.
I guess that the OPTION request sent to create.php is failing. Maybe because your backend code is trying to perform the action even in this case. OPTION requests should terminate only with CORS headers and an empty body. You can check this with a REST client (Postman for example).
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);
}
});
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
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