I'm new to the .Net development and i want to make a call to the client server. When i'm running the lines of code with POSTMAN, it runs pretty well. But when i'm using the same code/headers in java script i'm able to get the desired result.
Below is the line of code i'm using
var xhr = new XMLHttpRequest();
var params = "grant_type=password";
xhr.open("POST", "ClientURL");
xhr.setRequestHeader("Authorization", "Basic ZDJWQ1NmE4NjA4MDc0MjQ2NzSfdsdakj=");
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Data-Type", "json");
xhr.setRequestHeader("Host", "URL");
xhr.send(params);
console.log(xhr.status);
console.log(xhr.statusText)
Or
$.ajax({
type: "POST",
url: 'CLIENT URL',
dataType: "json",
headers: { 'Authorization': 'Basic ZDJWQ1NmE4NjA4MDc0MjQ2NzSfdsdakj=' },
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', 'Basic "ZDJWQ1NmE4NjA4MDc0MjQ2NzSfdsdakj="');
},
success: function (data) {
if (data) {
alert(data);
}
else {
alert("Something went wrong");
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert(thrownError);
}
});
Is there anything missing in the call? Any help is appreciated
Below it the error in IE
XMLHttpRequest: Network Error 0x80070005, Access is denied.
and in Chrome
Default.aspx:68 Uncaught SyntaxError: Failed to execute 'setRequestHeader' on 'XMLHttpRequest': 'Basic ZDJWQ1NmE4NjA4MDc0MjQ2NzSfdsdakj=' is not a valid HTTP header field value.
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', "Basic ZDJWQ1NmE4NjA4MDc0MjQ2NzSfdsdakj=");
},
change the function as above.
Related
I have this code and it works as expected when page loads, but when I'm trying to make that call after checking checkbox it will show Request header field x-csrf-token is not allowed by Access-Control-Allow-Headers in preflight response.
$.ajax
({
type: 'POST',
url: "https:/www.bb.com?uId=123&mId=123",
headers: {
"Accept": "application/json",
"Content-Type": "application/json",
},
beforeSend: function (xhr) { xhr.setRequestHeader("Authorization", "Basic dTHIgdfgsjdhgfsgfjhsfghsfkjs879"); },
dataType: 'json',
success: function (data) {
console.log(data);
},
error: function (xhr, status, error) {
console.log(xhr);
console.log(status);
console.log(error);
}
});
and for checking:
$("input:checkbox[name=list]").click(function () {
if ($(this).is(':checked')) {
do that call
}
});
any Idea how to sole that?
ok, so that was fixed by a backend code release. Thanks all for help
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.
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);
Here I have two for me the same request: jquery ajax and XMLHttpRequest but JQ ajax dont work... SO want to know what is the difference:
JQ ajax:
var urlAjax = "http://www.agroagro.com/v1/register";
$.ajax({
type: "POST",
url: urlAjax,
contentType: "application/x-www-form-urlencoded",
data: {
name: "Mile3",
email: "new1#new.com",
password: "face1book"
},
crossDomain:true,
success: function(data) { console.log(data); },
error: function(data) {console.log(data); },
dataType: 'json',
beforeSend: function (xhr) {
xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
},
headers: {
'Access-Control-Allow-Origin': '*'
}
});
});
});
and this ajax request dont work... give me 404 error...
XMLHttpRequest:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {"done"}
}
xhr.open("POST","http://agroagro.com/v1/register",true);
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhr.send("name=Henry&email=Ford#ford.com&password=1234");
This request work fine, but I need to know what is the difference, the both call POST url...
Also what I need to change in my JQ ajax request to work?
Access-Control-Allow-Origin is a response header so it shouldn't be on the list of request headers: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#The_HTTP_response_headers
Remove the following:
beforeSend: function (xhr) {
xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
}
and
headers: {
'Access-Control-Allow-Origin': '*'
}
I am having a problem with Sharepoint Rest social API.
Here's the code to like a post I got from googling around
function likePost() {
var postId = '1.0f435d74164149cfa76e19ad21dc7c2e.8a7874906a9348189f2fb83295b598d5.06ff4087162c48dcb43828e4ddf82c38.98b9fc73d5224265b039586688b15b98.8ec3fc561f084e6b98bfb117e9c23022.64.64.1';
$.ajax( {
url: "/_api/social.feed/Post/Like",
type: "POST",
headers: {
"accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
},
data: JSON.stringify({
'ID': postId
}),
success: function (data) {
alert("Success");
var jsonObject = data.d.ID;
alert(jsonObject);
},
error: function (xhr, ajaxOptions, thrownError) {
alert("POST error:\n" + xhr.status + "\n" + thrownError);
}
});
}
However when I try this on my Sharepoint site, I always get 403 FORBIDDEN error.
Any help would be appreciated.
In your application, you need to go into the AppManifest, go to the permissions, and give it permission to the "User Profiles (Social)" with at least Read permission.
This will allow your application to have access to the elements that it looks like you're trying to hit.
http://msdn.microsoft.com/en-us/library/jj163864.aspx