I'm having a problem to make a call to a rest API.
In the document (FAQ) of the web application there is an example that use AJAX request to make the call. Here an example:
var url = 'https://example.com/yyy';
$.ajax({
type: 'POST',
url: url,
cache: false,
data: {
opt: JSON.stringify(example)
},
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (result)
{
console.log(result);
} });
I created a local page with this code to made the post to the API that is located on a remote server but I receive an error about CORS.
Is there any solution to circumvent this problem? I tried to use firefox plugin to allow CORS but it didn't solve the problem. The session is authenticated via form before use the endpoint.
I see several issues:
Try to run the code from a domain and not from local disk (alternatively you can consider using https://crossorigin.me/ )
How does the authentication work? if with cookies you need to add withCredentials to the ajax request.
Make sure the API returns Access-Control-Allow-Origin: foo header where foo is the domain your code runs in. If you also used withCredentials, you should add Access-Control-Allow-Credentials: true
Related
I'm trying to use API Gateway as my server for a small database project, and I'm using Ajax to upload data to the server. I know I need to enable CORS to allow me to have cross-domain requests, and I've tried over and over multiple different methods of enabling CORS that I've found online, with no luck. No matter what I do, I seem to get the same error callback: {"readyState":0,"responseText":"","status":0,"statusText":"error"}
Here is the code I am using in the ajax request (for obvious reasons I omitted the URL of the API):
$.ajax({
type: 'POST',
url: API_URL,
data: data,
crossDomain: true,
dataType: "text",
contentType: 'text/plain',
success: (data, status, xhr) => {
alert("Success");
},
error: (e) => {
alert(JSON.stringify(e));
}
});
CORS is in fact enabled in my API, I can confirm this by checking the integration response for my OPTIONS method (there's only one resource and the only methods that exist for it are POST and OPTIONS). Any pointer in the right direction would be appreciated, trying to make this work has been very frustrating.
I'm writing a web page to let others can trigger the some jobs' build with parameters in jenkins. So I use ajax to send POST request:
var urlString = "http://localhost:8080/job/myjob/buildWithParameters";
$.post(
urlString,
{myParam:"there is some data"},
function(data)
{
alert(data);
},
"json"
);
But I got Http 403 response:
XMLHttpRequest cannot load http://localhost:8080/job/myjob/buildWithParameters. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access. The response had HTTP status code 403.
I know the cross site problem , but I cannot search any helpful information from Google, can ajax do this job?
UPDATE:
I found a similar question
So I update my code to :
$.ajax({
type: "POST",
url: urlString,
dataType: 'jsonp',
data: {},
beforeSend: function(xhr){
xhr.setRequestHeader("Authorization", "Basic " + btoa("admin:123456"));
},
success: function(data) {
},
complete: function(xhr, statusText){
}
});
I can confirm the username and password is correct , but I got 405 Method Not Allowed. Is there anything wrong?
Put your web page in the userContent folder under $JENKINS_HOME directory. Then open $JENKINS_URL/userContent/yourwebpage.html in your browser. Now the javascript in the page is loaded from the same origin where ajax calls will go, so it should be allowed without CORS tricks.
Jenkins want a POST not a GET HTTP request, a JSONP request is a GET: you can't do that :D
You can try to do in these way:
Startup jenkins with the AJP binding as described here
Configure Apache2 httpd as a reverse proxy for the Jenkins AJP
Force in Apache2 response header as described here to enable CORS
At the end you can use directly POST instead of JSONP.
have fun with XSS :D
I'm trying to access an API service (via XMLHttpRequest/ajax) hosted on a sub-domain (ie: a client on app.samedomain.com will call out to api.samedomain.com) that requires specific headers to be set for security purposes, but I keep getting Access is denied errors. All the solutions I've found say the client/end user must add the site to the "Trusted Sites" security zone, but obviously this is not a real solution. What do I need to do to access an external site with specific headers?
Example Code:
var getUserById = function (user, callback, error) {
$.support.cors = true;
var endpoint = _getApiVersion() + '/person/model/' + user.userId;
var _headers = _setHeaders(endpoint, null, user, 'GET');
$.ajax({
type: 'GET',
beforeSend: function (request)
{
request.setRequestHeader("api-key", _headers['api-key']);
request.setRequestHeader("timestamp", _headers['timestamp']);
request.setRequestHeader("content-md5", _headers['content-md5']);
request.setRequestHeader("content-type", _headers['content-type']);
request.setRequestHeader("signature", _headers['signature']);
request.setRequestHeader("Access-Control-Allow-Origin", "*");
},
url: _getBaseUrl() + endpoint,
data: null,
contentType: 'application/json',
dataType: 'json',
success: callback,
error: error
});
};
Thanks in advance,
Dan
Are you trying to get data that is not in the same domain as the requester? If that is the case the only option is to proxy the original request via a service so XMLHttpRequest has access to it.
"Access-Control-Allow-Origin" is a response header, not a request header. It is something that the server should send back to IE as part of the response.
If that still doesn't work, you might want to try firing up the F12 Network tool in the IE Dev tools to see if you can get more detail into where in the process the request is failing (Ex: It might be failing on a CORS preflight OPTIONS request).
Also, Rather than using "Access-Control-Allow-Origin: *", you should use "Access-Control-Allow-Origin:app.samedomain.com" to control which domains can access the API
To read more about CORS, check http://www.w3.org/wiki/CORS
Aside from that, it feels like an order of operations thing. All this should be before the callbacks.
type: 'GET',
url: _getBaseUrl() + endpoint,
data: null,
contentType: 'application/json',
dataType: 'json',
I would like to call OData .NET web service that authenticates users via basic authentication.
I use following ajax call:
var fullUri = APIUri + "?$format=json";
$.ajax({
url: fullUri,
contentType: "application/json",
dataType: "jsonp",
type: 'GET',
jsonp: '$callback',
beforeSend: function setHeader(xhr) {
xhr.setRequestHeader('Authorization', token);
},
success: callback,
error: function (xhr, ajaxOptions, thrownError) {
alert(thrownError);
},
});
The results are unusable for me:
Calls are blocked because of CORS (until I will paste API url and try to load it in chrome). I tried local html file and html file uploaded to the same domain/port, but authentication fails (according to Chrome console).
Once I enter service URL into chrome address bar, I am asked to provide login name and password by Chrome. If I enter them, they are cached and used even I assign them in beforeSend. How to blocks this behavior?
I've tried a lot of examples how to configure jsonp, headers etc, but did not find working solution yet.
IIS server response header is also configured using "Access-Control-Allow-Origin" value="*".
You can set the HTTP Password and Username in the AJAX Call directly:
$.ajax({
url: fullUri,
contentType: "application/json",
username: <login>,
password: <password>,
...
Use the following to support CORS:
jQuery.support.cors = true;
Regarding the call, are you using HTTPS? Is the certificate valid?
I had called the GET REST API by following code :
$.getJSON('http://myapisite.com/user/1?callback=?', function(msg){
console.log(msg);
});
But for calling DELETE REST API through jquery
what i had tried is :
$.ajax({
url: 'http://mysite.com/user/1?callback=?',
type: 'DELETE',
dataType: 'json',
data: '',
success: function(response) { console.log('PUT completed'+response); }
});.
and this api is not being called , I want to know how should i call the DELETE REST API .
Thanks
You are trying to do a cross-domain request. This means that you cannot use XMLHttpRequest (the basis of AJAX) because of the same-origin policy. You are using a workaround called JSONP, which works by inserting <script> tags into your document.
Script tags will always fetch content via GET, so you can't do a DELETE, POST, PUT or suchlike with them.
The best workaround would be to have a script on your own server that proxies the DELETE request for you.