I've seen similar incidents such as this. However, none of them seem to encounter the same problem I am having: Making a POST request and getting a 500 Internal Server Error in response.
I'm attempting to convert either of the following AJAX or XHR that I generated from a postman command to the AngularJS method of using the $http service:
The xhr:
var data = "json=<lots of encoded text>";
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
if (this.readyState === 4) {
console.log(this.responseText);
}
});
xhr.open("POST", "https://myJenkins.com/job/Ansible_Deploy/build?token=<build_token>");
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Authorization", "Basic <auth data>");
xhr.send(data);
The ajax:
var settings = {
"async": true,
"crossDomain": true,
"url": "https://myJenkins.com/job/Ansible_Deploy/build?token=<build_token>",
"method": "POST",
"headers": {
"content-type": "application/x-www-form-urlencoded",
"authorization": "Basic <auth data>"
},
"data": {
"json": "<raw json text>"
}
};
$.ajax(settings).done(function (response) {
console.log(response);
});
The broken AngularJS implementation:
var heads = new Headers();
heads.append('Content-Type', 'application/x-www-form-urlencoded');
heads.append('Authorization', 'Basic <auth data>');
$http({
url: "https://myJenkins.com/job/Ansible_Deploy/build?token=<build token>",
method: "POST",
data: <json object>,
headers: heads
}).then(function successCallback(response) {
console.log(response.data);
}, function errorCallback(response) {
console.log(response.statusText);
});
Both of the above Ajax and xhr implementations work fine. As mentioned above, the angular approach is giving me a 500 Internal Server Error.
Any ideas why this may be happening? I can provide specifics if they may help, such as information from the network tab on the chrome inspector. Just let me know what I should take a screenshot of and I'll post it here.
EDIT: As promised in the comments, my solution is below.
$http({
url: "https://myJenkins.com/job/Ansible_Deploy/build?token=<build token>",
method: "POST",
data: 'json=' + JSON.stringify(data),
headers: {
'Accept': "*/*",
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic <auth data>'
}
}).then(function successCallback(response) {
console.log(response.data);
}, function errorCallback(response) {
console.log(response.statusText);
});
EDIT 2: If you stumble upon this question because you're also getting a 500 Internal Server Error and still don't understand how this was resolved, then it was resolved via a combination of ensuring that CORS was setup on the server containing the endpoint (indicated by Crome's inspector throwing Access-Control-* errors) as well as correctly formatting the x-www-form-urlencoded to be accepted by Jenkins, which requires the data being sent to be of the form json={"parameter":[{"name":<key>, "value":<value>}, ...]}. Furthermore, if the value of an entry is a nested then escaping is required. see this answer for more details.
Related
I used postman to test my web service. In the http response body, I find the WS's response.
When I test my call, in my web application, using ajax, I can not find the response anymore. The tab contains a message saying "This request has no response data available."
this is my ajax call:
$.ajax({
url: url,
method: "POST",
data: params,
success:function(response) {
console.log(response); // no console here!
console.log('response');
},
error:function(){
console.log("error");
}
});
Hi, Try like this.
In the ajax, you are passing params, it should contain something like action = get_pincodes.
while handling this, action = get_pincodes.
you must write echo json_encode($responce);exit;
EX:
if($_REQUEST['action'] != "" && $_REQUEST['action'] == 'get_pincodes'){
$responce = array();
$responce[] = "500113";
$responce[] = "500114"; // etc....
echo json_encode($responce);exit;
}
maybe Adding charset=utf-8 to Content-Type in the response headers could solve the issue : Content-Type: application/json; charset=utf-8
$.ajax({
url: url,
method: "POST",
dataType: "json",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json;charset=utf-8'
},
data: params,
success:function(response) {
console.log(response); // no console here!
console.log('response');
},
error:function(){
console.log("error");
}
});
try to check if the XHR filter is selected and dont forget to reload the page afterwards
I am trying to send my selection to a server using post and server need REST, Tested my data with Advanced Rest Client and all works well, But when I try from my chrome extension I am getting undefinded error. Here is what I am trying
chrome.runtime.sendMessage({
method: 'POST',
action: 'REST',
headers: {'Remote-User':'myuser'},
url: 'http://myserver/data/add/',
data: {'content': 'the paste content'}
}, function(responseText) {
alert(responseText);
});
Any help much appreciated, thanks
Update
Based sdc, I changed my code like this and still responseText is undefined :(
function genericOnClick(info, tab)
{
var url = 'http://mysite/data/add/';
var data = $.toJSON({'content': 'the paste content'});
$.ajax({
headers: {
'Remote-User':'username',
'Content-Type':'application/json;charset=utf-8'
},
url: url,
data: data,
method: 'POST',
dataType: 'json',
error: function(xhr, status, error){
alert(xhr.responseText);
},
success: function(data){
console.log('succes: '+data);
}
});
}
I think you misunderstand the purpose of chrome.runtime.sendMessage. See the first two paragraphs of the Message Passing documentation. sendMessage is used for "communication between extensions and their content scripts" it is not designed for sending an HTTP request.
A content script must also "set up a runtime.onMessage event listener to handle the message" only then will you receive a valid response from the sendMessage request
The result from their example is undefined
chrome.runtime.sendMessage({greeting: "hello"}, function(response) {
console.log(response.farewell);
});
<- undefined
If you are attempting to perform a HTTP request from within your chrome extension, you should use XHR
var data = $.toJSON({'content': 'the paste content'});
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://myserver/data/add/", true);
xhr.setRequestHeader("Content-type", "application/json");
xhr.setRequestHeader("Content-length", data.length);
xhr.setRequestHeader("Connection", "close");
xhr.setRequestHeader('Remote-User', 'myuser');
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
console.log('xhr response: '+ xhr.responseText);
}
}
xhr.send(data);
I have a angularjs function which is calling a server side url and getting responses. This server side some times returning a xml response. sometimes returning a blog as the response. Can't predict. If I set the response type to "blob" in client side, it is showing image properly. But I cannot handle non blob responses because of xml responses also showing as a blob. Searched a lot in web about converting blob to xml(response containing a xml response). But couldn't find an answer :(
If I remove the response type: "blob", can handle the non blob response but cannot handle blob response.
Is there a way to handle both type of responses in a single method?
this is my angularjs code for getting response
$http({
url: apiConstants.BASE_URL + 'login',
method: "POST",
responseType: "blob",
data: {
"Req": req
},
headers: {
'X-Username': aUser,
'X-Password': aPass,
"Content-Type": "application/xml"
},
dataType: "xml"
}).success(function(data, status) {
console.log(data);
}
If you can manage to set the Content-Type header correctly in the response while serving your blob and xml responses from your server, then you can use the headers() in success callback to handle them accordingly.
$http.post(url, postData)
.then(function(response){
// success callback
var responseType = response.headers('Content-Type');
var actualType = responseType.split(';');
if(actualType[0] === 'application/xml'){
// handle XML files here
}else{
// handle blob files here
}
}, function(error){
// error callback
});
I solved this issue by doing following changes
$http({
url: apiConstants.BASE_URL + 'login',
method: "POST",
responseType: "blob",
data: {
"Req": req
},
headers: {
'X-Username': aUser,
'X-Password': aPass,
"Content-Type": "application/xml"
},
dataType: "xml"
}).success(function(data, status, headers, config) {
var responseType = headers('Content-Type');
if(responseType === 'application/xml;charset=utf-8'){
alert("xml");
}else{
alert("blob");
}
}
I am trying to call Neo4j API from jquery.
when i am invoking GET requests it works perfectly
GET request endpoint
http://localhost:7474/db/data/node/10
but when i am invoking POST requests with json body it returns following error.
POST request endpoint
http://localhost:7474/db/data/cypher
Error Message
"NetworkError: 500 Server Error - http://localhost:7474/db/data/cypher"
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:7474/db/data/cypher. This can be fixed by moving the resource to the same domain or enabling CORS.
When i try from Advance REST Client, it returns correct response. Please refer following code
$(document).ready(function(){
$("#btnQuery").click(function(){
var Request = "{'query' : 'MATCH (Movie { name:{searchName} })-[SHOWS]-(Cinema) RETURN Cinema','params' : {'searchName' : 'Rio 2'}}";
//url = mainURL +"cypher";
url = "http://localhost:7474/db/data/cypher";
$.ajax({
url: url,
headers : {
'Authorization' : 'Bearer 5f0e0d8c2a5477d4a8e79fa2d34f84a'
},
crossDomain: true,
type: 'POST',
dataType: 'application/json',
complete: function(xhr) {
if (xhr.readyState == 4) {
if (xhr.status == 201) {
alert("Data is loaded");
clearUsers();
isUserAdd = false;
}
} else {
alert("Data is not loaded");
}
},
beforeSend: function (xhr) {
xhr.setRequestHeader("accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
},
data: ('(' + Request + ')')
});
});
});
I have a working example here: http://jexp.github.io/cy2neo
Check out the code: https://github.com/jexp/cy2neo/blob/master/scripts/neo.js#L8
I think the problem was dataType: JSON which caused jquery to send a pre-flight header w/o CORS. I changed it to specifying content-type: JSON
I'm currently having issues making an external GET request for an API that I need to call and retrieve data from dynamically in JSON. Does anyone know what below may be incorrect? The main issue seems to be that the header information for the Authentication field is not being set correctly and that javaScript can't call out of local domains. I desperately need a work around to this : (error: XMLHttpRequest cannot load http://www.website.com/api.php. Origin http://localhost is not allowed by Access-Control-Allow-Origin.)
function requestDealer(url)
{
alert("looking up dealer");
var request = new XMLHttpRequest();
$.ajax({
url:url,
type: 'GET',
data: null,
Accept : "application/json",
contentType: "application/json",
success: function() { alert('hello!'); },
error: function() { alert('boo!'); },
beforeSend: setHeader
});
}
function setHeader(xhr) {
xhr.setRequestHeader('Authorization', 'NLAuth nlauth_account=23984390, nlauth_email = email#email.com, nlauth_signature= myPwrd');
xhr.setRequestHeader('Content-Type', 'application/json');
}