I'm using this part of the Outlook API. It says that you should be able to do a post request, however when I try I get the following error:
Failed to load https://login.microsoftonline.com/common/oauth2/v2.0/token: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3003' is therefore not allowed access. The response had HTTP status code 400.
How do I fix this though? I obviously don't have access to Outlook's servers, but surely they would let me do a post request considering that's what it says to do in the documentation!.
Here is my code by the way if that helps:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
let url = new URL(window.location);
let code = url.searchParams.get('code');
let redirect = 'http%3A%2F%2Flocalhost%3A3003%2Fauth-process-token.html';
let clientId = '<MY ID>';
let clientSecret = '<MY KEY>';
var req_string = 'grant_type=authorization_code&code=' + code + '&redirect_uri=' + redirect + '&client_id=' + clientId + '&client_secret=' + clientSecret;
$.ajax({
type: 'POST',
url: 'https://login.microsoftonline.com/common/oauth2/v2.0/token',
crossDomain: true,
data: req_string,
dataType: 'application/x-www-form-urlencoded',
success: function (responseData, textStatus, jqXHR) {
var value = responseData.someKey;
},
error: function (responseData, textStatus, errorThrown) {
console.log('POST failed.', errorThrown);
}
});
</script>
EDIT: I fixed the "bad request" error, but it still gives me the other one.
One workaround for this is by using cors.io
http://cors.io/?http://your_link
so it would be
http://cors.io/?https://login.microsoftonline.com/common/oauth2/v2.0/token
Related
I'm having some issues with the "Cross-Origin Request Blocked". I tried to allow first from the server, than from all ("*"). Got every time the same error message on the chrome developer toolkit.
Here is my flask python code:
application = Flask(__name__)
application.config.from_object(__name__)
cors = CORS(application, resorces={r'/*': {"origins": '*'}})
#application.route("/get-live-data",methods=['GET'])
#cross_origin()
def live_data():
con = connect_db()
cur = con.cursor()
cur.execute("SELECT * from envoiContinuT")
sqlite_result = cur.fetchall()
cle = json.load(open(JSON_STATUS))
parametres = json.load(open(JSON_PARAMETRES))
descT = []
for key in cle["status"]:
attr = parametres[key]
if attr["envoiC"] == 1:
descT.append(attr["description"])
response = any_response(flask.jsonify(data=descT))
return response
Here is my Ajax code:
var baseURL = "http://localhost:8000";
function getLiveData(data){
//Get the parameters descriptions
$.ajax({
method: 'GET',
url:baseURL + '/get-live-data',
headers: {
"Accept" : "application/json",
"Content-type": "application/json"
},
success:function(data){
console.log(data);
//populateAccordion(data);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log("Status: " + textStatus);
console.log("Error: " + errorThrown);
}
});
}
Thank you for your answer!
You have a typo here:
cors = CORS(application, resorces={r'/*': {"origins": '*'}})
^^^^^^^^
Should be:
cors = CORS(application, resources={r'/*': {"origins": '*'}})
Also, there’s no point in sending a Content-type request header for GET request. There’s no request body for GET requests, so no need to specify a content type. So instead just do this:
headers: {
"Accept" : "application/json",
},
Otherwise, if you send a Content-Type request header with the value application/json, that triggers your browser to do a CORS preflight OPTIONS request, and your config must allow it:
#application.route("/get-live-data",methods=['GET', 'POST'])
#cross_origin(headers=['Content-Type']) # Send Access-Control-Allow-Headers
But if you allow the Content-Type request header, you might as well allow POST requests too (as above)—since as mentioned earlier here, there’s no point in allowing it just for GET requests.
I'm using a node.js script that load in-built https package. When using it I get error:
XMLHttpRequest cannot load [constructed-api-url]. A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin' header when the credentials flag is true. Origin 'http://localhost:3000' is therefore not allowed access. The credentials mode of an XMLHttpRequest is controlled by the withCredentials attribute.
I'm using node.js 4.4.3, and its https api docs does not really mention anything about withCredentials.
The script being used is this one.
Is there anyway to set the xhr call's withCredentials to false using node.js https?
I am looking to something analogous to this jquery ajax call (just focusing on the xhr field):
$.ajax({
type: 'POST', async:true,
url: 'https://someapp.constructed.url/token',
dataType: "json",
contentType: 'application/x-www-form-urlencoded; charset=utf-8',
xhrFields: {
withCredentials: true
},
headers: {
'Authorization': 'Basic ' + appInfo
},
success: function (result) {
var token = result.access_token;
//…
},
error: function (req, status, error) {
if (typeof(req) != 'undefined') {
var msg = status || req.responseJSON.error;
//…
}
}
});
There is another very similar example, but this is related to the request package, which I don't want to include in dependencies. Beside, my used script is already using https.
So the answer was there all the time, after all:
After a bit of research, found that node's https package uses practically same options as http, including the withCredentials option (not documented in node's http/https, but part of xhr documentation). It was a matter of including the url option within the options object along the withCredentials option, and then pass the options object as parameter for https.get.
And the constructed code would be more or less as follows (focus on the options variable):
var options = {
url: 'https://my.domain.com/api/endpoint',
withCredentials: false
}
var querystring = '?key=' + [_my_api_key];
var param1 = '&' + [paramKey] + '=' + [paramValue];
var datos;
options.url += querystring;
options.url += param1;
https.get(options, function (res) {
res.on('data', function (data) {
datos += data;
});
res.on('end', function () {
try {
var data = JSON.parse(datos);
} catch (e) {
console.error('Unable to parse response as JSON', e);
}
});
}).on('error', function (e) {
console.error('An error occurred with the request:', e.message);
callback(e.message);
});
cross domain not working
have error in console like this
No 'Access-Control-Allow-Origin' header is present on the requested resource
im using html page in asp.net with json
my json code is
function beginCompile() {
setControlsEnabled(false);
clearOutputWindow();
var sourceCode = window.cseditor.getValue() || document.getElementById("sourcecode").value;
//alert(sourceCode);
setStatus("Compiling...");
$.ajax({
type: "POST",
url: "http://jsil.org/try/compile.aspx",
contentType: "text/plain; charset=UTF-8",
cache: false,
dataType: "json",
data: sourceCode,
success: compileComplete,
error: function (xhr, status, moreStatus) {
compileComplete(false, status + ": " + moreStatus);
},
});
};
function compileComplete(data, status) {
setControlsEnabled(true);
if (data && data.ok) {
setJavascript(data.javascript);
setStatus(
"Compile successful.<br>" +
"C# compile took " + data.compileElapsed + " second(s).<br>" +
"Translation took " + data.translateElapsed + " second(s)."
);
highlightErrorLines(null);
runInOutputWindow(data.javascript, data.entryPoint, data.warnings);
} else {
var errorText = String(data.error || status);
highlightErrorLines(errorText);
}
};
when i execute my page this code i have error
XMLHttpRequest cannot load http://jsil.org/try/compile.aspx. No 'Access-Control-Allow-Origin' header is present on the requested resource
I'm having trouble with this code and I can't seem to get it to work. The typical error that I get back for this call is a "Failed to load resource: the server responded with a status of 401 (Unauthorized) " .
$('#btnZendesk').click(function () {
$.ajax({
url: "https://flatlandsoftware.zendesk.com/api/v2/topics/22505987.json",
type: 'GET',
crossDomain: true,
xhrFields: {
withCredentials: true
},
cache: false,
dataType: 'jsonp',
processData: false,
data: 'get=login',
timeout: 2000,
username: "test#test.com",
password: "test",
success: function (data, textStatus, response) {
alert("success");
},
error: function (data, textStatus, response) {
alert(data);
}
});
Problem is that the resource you are trying to access is protected with Basic Authentication.
You can use beforeSend in jQuery callback to add a HTTP header with the authentication details e.g.:
beforeSend: function (xhr) {
xhr.setRequestHeader ("Authorization", "Basic XXXXXX");
}
Alternatively you can do it using jQuery ajaxSetup
$.ajaxSetup({
headers: { 'Authorization': "Basic XXXXX" }
});
EDIT
A few links to the mentioned functions
jQuery.ajaxSetup
jQuery.ajax
EDIT 2
The Authorization header is constructed as follows:
Username and password are joined into a string "username:password" and the result string is encoded using Base64
Example:
Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
I too got this problem and somehow all solutions from internet either failed or were not applicable due to client webservice restrictions (JSONP, XDR, CORS=true)
For this, I added an iframe in my page which resided in the client;s server. So when we post our data to the iframe and the iframe then posts it to the webservice. Hence the cross-domain referencing is eliminated.
We added a 2-way origin check to confirm only authorized page posts data to and from the iframe.
Hope it helps
<iframe style="display:none;" id='receiver' name="receiver" src="https://iframe-address-at-client-server">
</iframe>
//send data to iframe
var hiddenFrame = document.getElementById('receiver').contentWindow;
hiddenFrame.postMessage(JSON.stringify(message), 'https://client-server-url');
//The iframe receives the data using the code:
window.onload = function () {
var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var eventer = window[eventMethod];
var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
eventer(messageEvent, function (e) {
var origin = e.origin;
//if origin not in pre-defined list, break and return
var messageFromParent = JSON.parse(e.data);
var json = messageFromParent.data;
//send json to web service using AJAX
//return the response back to source
e.source.postMessage(JSON.stringify(aJAXResponse), e.origin);
}, false);
}
I just can't get the ajax service to work. A simple class to $.get("http://google.com") does not work. Also, this code does not work, too:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
</head>
<body>
<script>
$.ajax({
url: "http://google.com",
dataType: "html",
success: function(data, status) {
console.log("Success:");
console.log(" Data: " + data);
console.log(" Status: " + status);
},
error: function(request, status, error) {
console.log("Error:");
console.log(" Request: " + request);
console.log(" Status: " + status);
console.log(" Error: " + error);
},
});
</script>
</body>
</html>
saved in test.html.
This is the output on the console:
Error:
Request: [object Object]
Status: error
Error:
And these are the, I guess, important values of the returned object:
readyState 0
responseText ""
status 0
statusText "error"
Why does the request not work?
Thank you,
You can't use AJAX to access cross-domain scripts like that. This is because of the Same Origin Policy -- something which has been implemented for security reasons:
This mechanism bears a particular significance for modern web
applications that extensively depend on HTTP cookies to maintain
authenticated user sessions, as servers act based on the HTTP cookie
information to reveal sensitive information or take state-changing
actions. A strict separation between content provided by unrelated
sites must be maintained on client side to prevent the loss of data
confidentiality or integrity.
So you have a few options:
Just call scripts on your own server
Call scripts on your server which can communicate with third-party sites/apps/scripts
Use either JSONP or XML as a callback format.
You cannot make a request to another domain due to the same-origin-policy. See http://api.jquery.com/jQuery.ajax/ for more information.
You could use JSONP to achieve cross domain communication.
http://en.wikipedia.org/wiki/JSON#JSONP
But for plain html you have yo be on the same domain.
$.ajax({
url: "http://google.com",
dataType: "jsonp",
success: function(data, status) {
console.log("Success:");
console.log(" Data: " + data);
console.log(" Status: " + status);
},
error: function(request, status, error) {
console.log("Error:");
console.log(" Request: " + request);
console.log(" Status: " + status);
console.log(" Error: " + error);
},
});
EDIT:
But if your URL doesn't return a valid formatted json, your request will fail.
For a working example check:
http://jsfiddle.net/S3tAR/1/