I've done a new database with a user interface (with Javascript code) and Iam trying to connect the UI with TFS API to get some informations and save it in my Databas
but i have challenge in establishing this connectioin with Javascript
can anyone help me please??
If you want to do this via a javascript client, you could use the invoke as follows:
var self = this;
self.tasksURI = 'https://<SERVER>/tfs/<COLLECTION>/<PROJECT>/_apis/build/builds?api-version=2.0';
self.username = "<USERNAME>"; //basic username so no domain here.
self.password = "<PASSWORD>";
self.ajax = function (uri, method, data) {
var request = {
url: uri,
type: method,
contentType: "application/json",
accepts: "application/json",
cache: false,
dataType: 'json',
data: JSON.stringify(data),
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", "Basic " + btoa(self.username + ":" + self.password));
},
error: function (jqXHR) {
console.log("ajax error " + jqXHR.status);
}
};
return $.ajax(request);
}
self.ajax(self.tasksURI, 'GET').done(function (data) {
alert(data);
});
More details please refer this similar question in SO: TFS 2015 REST API Authentication
Related
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);
}
});
I am trying to add records to CRM using Javascript but getting:
401 Unauthorized Error.
My question is how to get the token and use it inside the JavaScript function.
$(document).ready(function() {
$("#Save").click(function() {
var ProductDetails = new Object();
ProductDetails.ProductName = $("#txt_productName").val();
ProductDetails.ProductDetail = $("#txt_desc").val();
$.ajax({
url: "https://mycrm.dynamics.com/api/data/v9.1/Products",
type: "Post",
dataType: 'JSON',
data: ProductDetails,
contentType: 'application/x-www-form-urlencoded',
success: function(data) {
alert('Updated Successfully');
},
error: function(request, status, error) {
alert(request.status);
}
});
});
});
You need add Authorization information in Http Header. Here is an example if you use JWT.
$(document).ready(function() {
$("#Save").click(function() {
var ProductDetails = new Object();
ProductDetails.ProductName = $("#txt_productName").val();
ProductDetails.ProductDetail = $("#txt_desc").val();
$.ajax({
url: "https://mycrm.dynamics.com/api/data/v9.1/Products",
type: "Post",
headers: {
'Accept':'application/json',
'Content-Type':'application/json',
'Authorization':'Bearer your token here'
},
dataType: 'JSON',
data: ProductDetails,
contentType: 'application/x-www-form-urlencoded',
success: function(data) {
alert('Updated Successfully');
},
error: function(request, status, error) {
alert(request.status);
}
});
});
});
You have to add a header with the bearer token like this:
$.ajax({
(...)
headers: {
"Authorization": "Bearer " + token
},
(...)
In order to get a token you have to register an application in Azure Active Directory first, in the same tenant as your Dynamics 365 instance. Check this link if you need a thorough step by step guide to do it.
After registering you application in AAD you also have to add some code to do the authentication with Azure and getting the token. ADAL.js does this job for you, but keep in mind that it prompts the user to manually add his username and password in a office 365 popup. This is called interactive authentication and as far as I know it can't be avoided.
For a full HTML + JS working example click here.
I am trying to send a request using ajax to a server which is protected by basic authentication with the following code:
$('document').ready(function(){
$.ajax({
url: "https://somesite.com/somefolder",
type: "POST",
dataType: 'jsonp',
beforeSend: function(xhr) {
xhr.setRequestHeader ("Authorization", "Basic " + btoa('myusername' + ":" + 'mypassword'));
},
success: function(data){
console.log('SUCCESS!');
},
error: function () {
console.log("error");
}
});
});
So I provide the credentials in the beforeSend so my expectation would be that there would be no credential popup from the browser since I already provided the credentials but unfortunately when i run this code I get the popup to enter my credentials. I want to the code to provide these credentials.
Similar to this question, example using headers:
$.ajax({
url: "https://somesite.com/somefolder",
type: "POST",
dataType: 'jsonp',
headers: {"Authorization": "Basic " + btoa('myusername' + ":" + 'mypassword')},
success: function(data){
console.log('SUCCESS!');
},
error: function () {
console.log("error");
}
});
While calling the api from JavaScript
This HTTP request works fine https://api.pcloud.com/userinfo?username=xxxx#gmail.com&password=xxxx
In the below code I want to call via JavaScript
var user='email loggin';
var password='password of pcloud';
function make_base_auth(user, password) {
var tok = user + ':' + password;
var hash = btoa(tok);
return "Basic " + hash;
}
$.ajax
({
type: "GET",
url: "https://api.pcloud.com/userinfo",
dataType: 'json',
async: false,
data: '{}',
beforeSend: function (xhr){
xhr.setRequestHeader('Authorization', make_base_auth(username, password));
},
success: function (){
alert('Working Fine');
}
});
output in console
XMLHttpRequest cannot load https://api.pcloud.com/userinfo?{}. Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response.
If someone can provide a solution or enhance the code.
Pass the username and password in the data field and remove the "beforeSend" part. For more information and examples, you can check out the pCloud Javascript SDK: https://github.com/pCloud/pcloud-sdk-js
Here is working example (a bit shorter):
$.getJSON("https://api.pcloud.com/userinfo", {
username: "***",
password: "***"
}, function() {
alert("working fine");
});
I have a REST API and I am wanting to invoke it from my ajax javascript client.
I make the call and nothing happends. My mobile browser just indicates 'busy'.
No error is returned.
This is my code behind:
[HttpPost]
[Route("Services/Image/Validate")]
public byte Validate(string KeyCode)
{
return 1;
}
this is my JavaScript client:
$("#btnValidate").click(function () {
try {
var url = "http://MY_DOMAIN_NAME/api/Services/Image/Validate";
$.ajax({
type: 'POST',
url: url,
data: '{ "KeyCode" : "' + $("#KeyCode").val() + '" }',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (msg) {
$('#divStep1').hide();
$('#divStep2').show();
},
fail: function (a) {
$("#error").html(objRequest);
}
});
}
catch (ex)
{
$("#error").html(ex);
}
return false;
});
The catch function with throw an error only when the HTTP request fails. In Order to know wha'ts going wrong in the server side code you need to use the error function in the ajax request,
You also mentioned that the browser does nothing and this might happen due to
jQuery plugin not included in the page (check console for $ is not defined)
Add the jquery plugin above your javascript
If your server side code is on a different domain enable CORS
$("#btnValidate").click(function () {
var url = "http://MY_DOMAIN_NAME/api/Services/Image/Validate";
$.ajax({
type: 'POST',
url: url,
data: '{ "KeyCode" : "' + $("#KeyCode").val() + '" }',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (msg) {
$('#divStep1').hide();
$('#divStep2').show();
},
error: function (e) {
console.log(e.responseText); //Acutal error
console.log(e); //Get the entire error details
}
});
});
The settings object you are sending to $.Ajax() does not expect a fail parameter. Maybe you are confusing promises?
Anyway, it should probably be error.
eg.
$("#btnValidate").click(function () {
try {
var url = "http://MY_DOMAIN_NAME/api/Services/Image/Validate";
$.ajax({
type: 'POST',
url: url,
data: '{ "KeyCode" : "' + $("#KeyCode").val() + '" }',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (msg) {
$('#divStep1').hide();
$('#divStep2').show();
},
error: function ( jqXHR, textStatus, errorThrown) {
$("#error").html(textStatus);
}
});
}
catch (ex)
{
$("#error").html(ex);
}
return false;
});
Also, I'm not sure if you should have the data property as a string but maybe this is how you want it.
All documentation on this is HERE