Can't find difference between Fetch and JQuery Ajax - javascript

I'm trying to do API request to a private API (hosted Itop), there's an example in the doc with JQuery Ajax but I did all my others calls with fetch and I wanted to do this one too but I don't get the right response.
The fetch method returns me a code 200 but with HTML instead of JSON (with a totally different content from the jQuery AJAX JSON one).
Here's the 2 functions:
// Code made by myself - don't get the right response
fetch(url, {
method: "POST",
headers: {
"accept": "application/json",
},
mode: "cors",
accept: "application/json, text/javascript, *!/!*; q=0.01",
body: JSON.stringify({
auth_user: user,
auth_pwd: password,
json_data: JSON.stringify({
"operation": "list_operations",
})
})
})
.then(response => response.json())
.then(data => {
console.log(data);
})
// Code from the doc example - working
$.ajax({
type: "POST",
url: url,
dataType: "json",
data: {
auth_user: user,
auth_pwd: password,
json_data: JSON.stringify({
"operation": "list_operations"
})
},
crossDomain: 'true'
})
.then(
function(data, textStatus, jqXHR) {
console.log(data);
console.log(textStatus);
console.log(jqXHR);
},
function(jqXHR, textStatus, errorThrown) {
console.debug(jqXHR);
console.log("ERROR !!\n" +
"status: " + textStatus + " (" + jqXHR.status + ")\n" +
"error: " + errorThrown);
}
);

In jQuery.ajax, when you pass data an object:
it will be encoded as application/x-www-form-urlencoded data
jQuery will include a Content-Type: application/x-www-form-urlencoded header
In fetch, you are passing body a string of JSON and fetch will be including a Content-Type: text/plain header.
So:
You are passing the wrong encoding of data
You are passing a Content-Type that doesn't match what the server expects or what your data actually is
Pass fetch a URLSearchParams object.
This will be encoded with the correct format and fetch will infer the correct content type from it.

Related

How to convert a Raw body data request for an API to ajax request

I am currently using postman to make an API request that pushes body data. I can get this to work either using "x-www-form-urlencoded" or "raw". See examples below:
I'm trying to convert this to an ajax javascript request but unsure on how to format the body/data text. Here is my script:
$.ajax({
type: 'POST',
url: 'https://login.microsoftonline.com/***/oauth2/token',
headers: {
"Content-Type": "application/json"
},
data: {
" grant_type=client_credentials
&client_id=***
&client_secret=***
&resource=https://analysis.windows.net/powerbi/api "
},
success: (data) => {
console.log(data.token)
},
error: (data) => {
console.log('rr', data)
}
});
Any help would be appreciated
There's a mismatch here as you're setting the Content-Type header to JSON, yet you're sending form-urlencoded. You need to use one or the other consistently.
If you want to explicitly use JSON, do this:
$.ajax({
type: 'POST',
url: 'https://login.microsoftonline.com/***/oauth2/token',
contentType: 'application/json', // shorter than setting the headers directly, but does the same thing
data: JSON.stringify({
grant_type: 'client_credentials',
client_id: '***',
client_secret: '***'
resource: 'https://analysis.windows.net/powerbi/api'
}),
success: data => {
console.log(data.token)
},
error: (xhr, textStatus, error) => {
console.log('rr', error)
}
});
If you want to use a form-urlencoded string, do this:
$.ajax({
type: 'POST',
url: 'https://login.microsoftonline.com/***/oauth2/token',
data: 'grant_type=client_credentials&client_id=***&client_secret=***&resource=https://analysis.windows.net/powerbi/api',
success: data => {
console.log(data.token)
},
error: (xhr, textStatus, error) => {
console.log('rr', error)
}
});
Note in the above examples that the first argument to the error handler is not the request or response data as your example seems to expect. I've amended that part to accept the correct arguments.

Calling Mirth 'client api' services from jquery

I have a .Net website, hosted on an intranet web server. On the .Net site I have a basic jquery ajax call to our mirth machine. I'm trying to hit the client apis that are provided with the base install of mirth.
We are running mirth 3.9.1, with a default mirth.properties page, so the CORS settings should be correct.
I've tried a variety of settings in mirth.properties (and restarted mcservice between changes) and a variety of $.ajax settings, but cannot seem to find the right mix.
According to this answer: (https://stackoverflow.com/a/47096927/505829), I should be able to use basic authentication, but even if I have to make two calls, I'm ok with that, I just need something that works. Though one call would be preferred.
Here is the ajax call
$.ajax
({
type: "GET",
url: "https://ngmaintst01:8443/api/channels",
dataType: 'json',
// username: username,
// password: password,
// crossDomain: true,
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', 'Basic ' + btoa(username + ":" + password));
},
xhrFields: {
withCredentials: true
},
// headers: {
// "Authorization": "Basic " + btoa(username + ":" + password)
// },
success: function () {
alert('success');
}
});
Here is the mirth properties:
# CORS headers
server.api.accesscontrolalloworigin = *
server.api.accesscontrolallowcredentials = false
server.api.accesscontrolallowmethods = GET, POST, DELETE, PUT
server.api.accesscontrolallowheaders = Content-Type
server.api.accesscontrolexposeheaders =
server.api.accesscontrolmaxage =
If I take the one call aproach, illistrated above, in chromes dev console I get:
(failed)net::ERR_FAILED
If I take a two call approach (below), the first call is successful (code 200), and the second gets the same error as the single call approach '(failed)net::ERR_FAILED', This time it appears the second call does NOT go out with the cookie session data, which is why a single call approach may be ideal.
$.ajax({
type: 'POST',
url: 'https://' + APPLIANCE+':8443/api/users/_login',
contentType: 'application/x-www-form-urlencoded',
dataType: 'xml',
data: { username: username, password: password },
success: function (data, textStatus, jqXHR) {
//alert(textStatus);
$.ajax({
type: 'GET',
url: 'https://' + APPLIANCE + ':8443/api/channels/' + channelid + '/statistics',
dataType: 'xml',
crossDomain: true,
xhrFields: { withCredentials: true },
//data: data,
//success: function(data, textStatus, jqXHR){ alert(textStatus); },
//error: function(jqXHR, textStatus, errorThrown){ alert(textStatus);}
});
},
error: function (jqXHR, textStatus, errorThrown) { alert(textStatus); }
});
I was able to get this working with some help from the mirth folks on slack. There is a "problem" in that, as far as I know, it will only support one web server. So I either need to have both my test and prod site on this one server, or no test.
Alternatively, I will just use a proxy back end service to circumvent cors altogether. So my local js will call my local proxy server, and forward the request on to mirths api.
Still, for posterity, here is how to get cors to work.
(One possible feature for mirth to implement would be dynamic accesscontrolalloworigin, where you provide an 'access list' of domains, and so long as the request is coming from one of those domains, it spits out, dynamically, that servers name. This would enable me to have multiple servers calling these apis. ala Access-Control-Allow-Origin Multiple Origin Domains?)
# CORS headers
server.api.accesscontrolalloworigin = https://MyDomainServer
server.api.accesscontrolallowcredentials = true
server.api.accesscontrolallowmethods = GET,HEAD,OPTIONS,POST,PUT
server.api.accesscontrolallowheaders = Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers, Authorization
server.api.accesscontrolexposeheaders =
server.api.accesscontrolmaxage =
$.ajax
({
type: "GET",
url: "https://MirthAppliance:8443/api/channels",
dataType: 'json',
xhrFields: {
withCredentials: true
},
headers: {
"Authorization": "Basic " + btoa(username + ":" + password)
},
success: function () {
//alert('success');
},
error: function (xhr, status, error) {
var errorMessage = xhr.status + ': ' + xhr.statusText
// alert('Error - ' + errorMessage);
}
});

POST data to google contact api

I want to create new contact in google contact with google api with javascript and jquery, i can retrieve contacts with this sample :
jQuery.ajax({
url: "https://www.google.com/m8/feeds/contacts/default/full?alt=json&" +
"access_token=xs55.CjDOA8lRTs8567657567vXXXX&" +
"max-results=100&" +
"v=3.0",
headers: {
'Authorization': "Bearer xs55.CjDOA8lRTs8567657567vXXXX",
'Content-Type': 'application/json'
},
method: "GET",
dataType: 'jsonp',
success: function (data) {
console.log(data)
},
error: function (data) {
console.log('error: ');
console.log(data);
console.log(data.status);
}
})
Now i want to POST data and create or update items in google document there is always error ! :(
For example in this code "Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://XXX' is therefore not allowed access. The response had HTTP status code 405." error happened :
jQuery.ajax({
url: "https://www.google.com/m8/feeds/contacts/default/full?alt=json&" +
"access_token=xs55.CjDOA8lRTs8567657567vXXXX&" +
"max-results=100&" +
"v=3.0",
headers: {
'Authorization': "Bearer xs55.CjDOA8lRTs8567657567vXXXX",
'Content-Type': 'application/json'
},
method: "POST",
data: {title: "vvvv", phonenumber: "3333"},
//dataType: 'jsonp',
success: function (data) {
console.log(data)
},
error: function (data) {
console.log('error: ');
console.log(data);
console.log(data.status);
}
})
whitout jsonp option there is no way to work that this option used when want to GET something not POST it .
Can you try this:
data= {title: "vvvv", phonenumber: "3333"};
$.ajax({
type: "POST",
data :JSON.stringify(data),
url: "https://www.google.com/m8/feeds/contacts/default/full?alt=json&" +
"access_token=xs55.CjDOA8lRTs8567657567vXXXX&" +
//"max-results=100&" +
"v=3.0",
contentType: "application/json"
});

Youtube Upload JS with API -> get 405 Method not allowed

I can't upload videos to youTube with Javascript anymore. If I call the URL
$.ajax({
url: VIDEOS_UPLOAD_SERVICE_URL,
method: 'POST',
contentType: 'application/json',
headers: {
Authorization: 'Bearer ' + accessToken,
'x-upload-content-length': file.size,
'x-upload-content-type': file.type
},
data: JSON.stringify(metadata)
}).done(function (data, textStatus, jqXHR) {
...DO SOMETHING
}
})
I get an Error 405 Method not allowed, but a few days/weeks ago everything works fine :-(
The VIDEOS_UPLOAD_SERVICE_URL is https://www.googleapis.com/upload/youtube/v3/videos?uploadType=resumable&part=snippet
But if I call the ajax Request to fetch the categories that works fine...

Cross domain jquery ajax api call with custom headers is not hitting the server

I want to call a webservice from client side using jquery ajax(with custom headers). And I almost did that. I had set Access-Control-Allow-Origin to force.com and salesforce.com since I'm calling the webservice from salesforce.
When I try to call that API without the custom headers, its getting the response where as when I called with the headers, its not getting the response.
With custom headers
jQuery.ajax({
type: 'POST',
contentType: 'application/x-www-form-urlencoded',
url: 'https://xxx.myclient.com/xxx/xxx/register',
beforeSend: function(xhr) {
xhr.setRequestHeader('orgid', '00D90000000oxxxx');
xhr.setRequestHeader('userid', '00590000001Dxxxxxx');
},
success: function(response) {
alert('success' + JSON.stringify(response));
},
error: function(jqXHR, textStatus) {
alert('jqXHR : ' + JSON.stringify(jqXHR) + ' textStatus : ' + textStatus);
}
});
also tried with
jQuery.ajax({
type: 'POST',
contentType: 'application/x-www-form-urlencoded',
url: 'https://xxx.myclient.com/xxx/xxx/register',
headers: {
"orgid": "00D90000000oxxxx",
"userid": "00590000001Dxxxxxx",
},
success: function(data) {
alert(JSON.stringify(data));
},
error: function(jqXHR, textStatus) {
alert('jqXHR : ' + JSON.stringify(jqXHR) + ' textStatus : ' + textStatus);
}
});
But in both the above cases it is not hitting the server and getting the error message
When I'm not using any headers, then its hitting the server
jQuery.ajax({
type: 'POST',
contentType: 'application/x-www-form-urlencoded',
url: 'https://xxx.myclient.com/xxx/xxx/register',
success: function(response) {
alert('success' + JSON.stringify(response));
},
error: function(jqXHR, textStatus) {
alert('jqXHR : ' + JSON.stringify(jqXHR) + ' textStatus : ' + textStatus);
}
});
Its getting the success response
In response headers it shows that
Access-Control-Allow-Headers: Content-Type
Only content-type is there, Is that the problem?
Whether we need to add our custom headers here?
And when I analysed the network using firefox firebug, it is showing as given below
POST Register (without any headers passed)
OPTIONS Register (with custom headers)
I dont know why this is happening
Can any one help.
Thanks in Advance ..:)
Try adding your custom headers (orgId and userId) in the "Access-Control-Allow-Headers" list of the service you are calling.

Categories

Resources