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
Related
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
Currently in my web app project, I need to parse the content of a web page, and after some searching, I found that Mercury Web Parser API is quite suitable for me.
And I have some experience with such kind of third party APIs, generally speaking I can get my desired result.
But for this API, I can't find documentation about the API usage on the official website.
Based on the my study, it provide two methods:
first is cURL as following:
curl -H "x-api-key: myapikey" "https://mercury.postlight.com/parser?url=https://trackchanges.postlight.com/building-awesome-cms-f034344d8ed"
the myapikey is the API key I get from the website. Then I can get the result in JSON format, which is the main content of the web page specified by the url parameter. It works well for me, I mean the cURL method.
And on the website, it said that the second method is HTTP call, which is just what I need:
GET https://mercury.postlight.com/parser?url=https://trackchanges.postlight.com/building-awesome-cms-f034344d8ed
Content-Type: application/json
x-api-key: myapikey
So based on my understanding, I use jquery AJAX method to do this as following:
var newurl = "https://mercury.postlight.com/parser?url=http://www.businessinsider.com/joel-spolsky-stack-exchange-interview-2016-12&x-api-key=myapikey"
$.ajax({
url: newurl,
dataType: "jsonp",
success: function(data){
console.log(data.title);
}
})
here I made JSONP request because of the Cross origin issue.
But now I face 401 error message (401 Unauthorized. The request has not been applied because it lacks valid authentication credentials for the target resource)
For now my guess is that the apikey is not correctly passed to server. So based on the cURL's successful call, can I get the correct format for AJAX call?
Update:
Based on the following answers ,I tried to set the request header as following:
$.ajax({
url: newurl,
dataType: "jsonp",
beforeSend: function(xhr){
console.log(apiKey);
xhr.setRequestHeader('x-api-key', apiKey);
},
/*
headers: {
"x-api-key": "M1USTPmJMiRjtbjFNkNap9Z8M5XBb1aEQVXoxS5I",
"contentType": 'application/json'
},
*/
success: function(data){
console.log("debugging")
console.log(data.title);
},
error: function (error) {
console.log(error)
}
})
I tried both beforeSend and headers. But still can't work and get the following trackback error message:
send # jquery.js:8698
ajax # jquery.js:8166
addNewArticle # topcontroller.js:18
fn # VM783:4
e # angular.js:281
$eval # angular.js:147
$apply # angular.js:147
(anonymous) # angular.js:281
dispatch # jquery.js:4435
elemData.handle # jquery.js:4121
And for the last send function, still 401 error.
But the ajax error handling part shows that the readyState:4 and status: 404 result. So what's going here.
For your question, the curl request is sending a header which you have attached as part of the query string in your $.ajax request.
Try the following instead (using beforeSend + xhr) :
// broke this string down so you don't have to scroll
var newurl = "https://mercury.postlight.com/parser?" +
"url=http://www.businessinsider.com/" +
"joel-spolsky-stack-exchange-interview-2016-12";
// set your api key
var apiKey = "<your api key>";
$.ajax({
url: newurl,
dataType: "json",
beforeSend: function(xhr){xhr.setRequestHeader('x-api-key', apiKey);},
success: function(data){
console.log(data.title);
}
})
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'v been struggling with POST on the Picasa API.
Here's code:
$.ajax({
type: "POST",
url: 'https://picasaweb.google.com/data/feed/api/user/' + uid + '/albumid/' + album_id + '/photoid/' + photo_id,
crossDomain: true,
data: { content: content },
success: function() { alert("Success"); },
error: function() { alert('Failed!'); }
});
I've already retrieved some information via GET without problems.
Now comes the fun part, when I try to test the service with Google this error occurs:
XMLHttpRequest cannot load
https://picasaweb.google.com/data/feed/api/user/userid/albumid/albumid/photoid/photoid?content=foo%bar.
Origin http://localhost:3000 is not allowed by
Access-Control-Allow-Origin
.
And when I try in Firefox the request header method is changed to OPTIONS and status is 204: no content.
Also, I've tried to change datatype to jsonp but then HTTP method changes to GET and it retrieves information about the picture.
Access-Control-Allow-Origin is coming because your are making a ajax call to a server which is not same as your current domain.
Read more here
jsonp will not help for POST request because you can only make GET request with jsonp.
IMHO you should try to make the POST request from server side instead of client side script.
I'm having an issue getting this jQuery.ajax call to work. When the script executes I get an error (textStatus = "error"), but no error message (errorThrown = "").
$.ajax({
type: 'GET',
url: 'http://www.kanbanpad.com/api/v1/projects.json',
username: 'user#example.wtf',
password: 'myAPIkey',
dataType: 'json',
success: function(data) {
alert(data);
},
error: function(jqXHR, textStatus, errorThrown) {
alert(textStatus+': '+errorThrown);
}
});
If I manually hit the API URL (above) and type in my login credentials, I do get the proper JSON response. So, I'm not sure what I'm doing wrong. Is my code malformed?
If you need more information about the API, go to http://www.kanbanpad.com/api/v1
That page is using HTTP basic auth but you are simply posting a username/password in your request. You have to properly set up the auth tokens and pass them in a header. Here is a simple tutorial on HTTP basic auth over AJAX--notice there is a jQuery specific example for the AJAX part.
Here is the fix:
Change URL value to http://username%40domain.com:apikey#www.kanbanpad.com/api/v1...
For whatever reason, jQuery (1.5.1, also tried with 1.4.4) is not passing the username and password parameters to the web server correctly (or not at all?), so rather than use those parameters, it can authenticate by including the credentials in the URL string.
use secured protocol for URL: https://www.kanbanpad.com/api/v1/projects.json, not http