Dynamics CRM Web API Auth Error on Web Resource - dynamics-crm-online

When loading a Dynamics CRM form with a HTML web resource I get the below error from the Chrome browser console.
https:‌//xxxx.api.crm6.dynamics.com/api/data/v8.2/<custom entity>. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://.crm6.dynamics.com' is therefore not allowed access. The response had HTTP status code 401.
<script type="text/javascript">
var clientUrl = "https://xxxx.api.crm6.dynamics.com/api/data/v8.2/"
function GetAccounts() {
var url = clientUrl + "accounts"
$.ajax({
method: "GET",
url: url,
async: false,
beforeSend: getAccountsBeforeSendCallback,
fail: getAccountsFailCallback,
done: getSavingGoalsDoneCallback,
success: getAccountsSuccessCallback
});
}
function getAccountsBeforeSendCallback(jqXHR, settings) {
debugger
jqXHR.setRequestHeader("OData-MaxVersion", "4.0");
jqXHR.setRequestHeader("OData-Version", "4.0");
jqXHR.setRequestHeader("Accept", "application/json");
jqXHR.setRequestHeader("Content-Type", "application/json; charset=utf-8");
}
</script>

It seems you're doing a request to another domain. Are you sure your clientUrl is on same domain?
var clientUrl = "https://xxxx.api.crm6.dynamics.com/api/data/v8.2/";
var rightUrl = window.Xrm.Page.context.getClientUrl() + "/api/data/v8.2";
if (clientUrl !== rightUrl) {
console.log("You will get the 'Access-Control-Allow-Origin' error!");
}
A lot of people have trouble with the $.ajax and XmlHttpRequest stuff. Luckily there are libraries, which will take care for this. Example of crm-sdk, which will do same as your code:
<script type="text/javascript" src="CRMSDK.js"></script>
<script type="text/javascript">
var WebAPI = window.CRMSDK.WebAPI;
WebAPI.retrieveMultiple("account").then(function (data) {
getAccountsSuccessCallback(data); //this is your method.
});
</script>

Related

Rendering Django template with Ajax call by calling endpoint

I am using ModelViewSet to fetch objects from my database and rendering them in a Django template. Since JWT Authentication is needed, I am sending the token in the header of AJAX request. I get the response back but if I redirect to the correct page I get a 401 Unauthorised.
$.ajaxSetup({
headers: {
'Authorization': "Bearer " + window.sessionStorage.getItem("token")
}
});
$(document).ready(function () {
$("#id").on('click', function (event) {
event.preventDefault()
var url = "myurl"
$.ajax({
url: url,
type: 'GET',
dataType: "html",
tokenFlag: true,
success: function(res) {
location.href = url
}
});
});
});
I want the page to redirect and the template rendered. It works fine in Insomnia.

csrf-token mismatch error in laravel on server

I'm using this code to submit data through ajax in laravel
$('#submit').submit(function (e) {
e.preventDefault();
let formData = new FormData(this);
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
xhr: function() {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
percentComplete = parseInt(percentComplete * 100);
if (percentComplete === 100) {
}
}
}, false);
return xhr;
},
url: $(this).attr('action'),
type: "POST",
data: formData,
dataType:'JSON',
contentType:false,
cache: false,
processData: false,
but getting csrf token mismatch when i upload my code on live server.
Any solution is highly appreciated Thanks
I see you are fetching the token from the HTML page metatag, make sure your HTML page is not being cached by an intermediate/browser between accesses (try opening with two different browsers and checking the token, refreshing with f5 and force reloading too).
Another common issue is multiple HTML pages being loaded simultaneously (frames? maybe a 404 file that returns your default page, refreshing the token for your session). This is hard to find, check the network tab of your browser dev tools and inspect each response.
I don't think it's the case, but sometimes the case makes difference X-CSRF-Token if a proxy is "cleaning up non whitelisted headers".

Speech Service Authentication Issue on Bot Framework V4

Getting the following error while trying to get a token from Azure Speech Service.
'https://brazilsouth.api.cognitive.microsoft.com/sts/v1.0/issuetoken 401 (Access Denied)'.
Here is the way I'm requesting the token via JavaScript:
const res = await fetch('https://brazilsouth.api.cognitive.microsoft.com/sts/v1.0/issuetoken', { method: 'POST', headers: { Authorization: 'Bearer ' + 'MY_SPEECH_SERVICES_SUBSCRIPTION_KEY'}});
const { authorizationToken } = await res.json();
webSpeechPonyfillFactory = await window.WebChat.createCognitiveServicesSpeechServicesPonyfillFactory({ authorizationToken, region });
My bot works fine if I get a token manually via Windows PowerShell though.
What could be possibly wrong?
Thx in advance
Sharing a way to get the token via javascript.
The 'data' variable will be storing the token.
Thanks all for your support!
`<!DOCTYPE html>
<html>
<head>
<title>JSSample</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(function() {
var params = {
// Request parameters
};
$.ajax({
url: "https://brazilsouth.api.cognitive.microsoft.com/sts/v1.0/issuetoken" + $.param(params),
beforeSend: function(xhrObj){
// Request headers
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key","MY_SPEECH_SERVICES_SUBSCRIPTION_KEY");
},
type: "POST",
// Request body
data: "{body}",
})
.done(function(data) {
alert(data);
})
.fail(function() {
alert("error");
});
});
</script>
</body>
</html>`

Vue JS Ajax Calls

I am trying to make the change from jQuery to Vue.js and am having some difficulty running an Ajax Call using vueresource. Below is a sample script I am using, with both jQuery and Vuejs. Both trying to access the same ajax call. The jQuery call works, the vuejs call doesn't. The sendAjax method is being called because the first 2 alerts show - then nothing.
Edit - this is only causing an error while running the Ajax call through Wordpress. Outside of WP, it does work. Any ideas??
<!DOCTYPE html>
<html>
<head>
<title>Vue Resource</title>
<script src="https://cdn.jsdelivr.net/npm/jquery#3.2.1/dist/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/vue/latest/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue-resource#1.5.1"></script>
</head>
<body>
<button id="jQueryAjax">Jquery AJAX</button>
<div id="myvue">
<button #click.prevent="sendAjax()">AJAX</button>
</div>
<script>
let AjaxUrl = "http://localhost:8888/mySite/wp-admin/admin-ajax.php";
const postData = { action: 'my_ajaxcall', function: 'AjaxTest' };
Vue.use(VueResource);
const ajax_app = new Vue({
el: '#myvue',
methods: {
sendAjax() {
alert("VueAjax");
alert(JSON.stringify(postData));
this.$http.post(AjaxUrl, postData).then(res => {
alert(JSON.stringify(res));
});
}
}
});
$("#jQueryAjax").click(function() {
alert("jQueryAjax");
alert(JSON.stringify(postData));
alert(AjaxUrl);
$.ajax({
type: 'POST',
url: AjaxUrl,
data: postData,
dataType: 'json',
success: function(data) {
alert(JSON.stringify(data));
},
error: function (xhr, ajaxOptions, thrownError) {
alert("Error");
}
});
});
</script>
</body>
</html>
You AJAX call probably encounters an error and you handle only the successful calls. Please extend your sendAjax function like this:
this.$http.post(AjaxUrl, postData).then(res => {
alert(JSON.stringify(res));
}, err => {
alert(err);
});
Now an error should be alerted.
BTW: It is better to use console.log() instead of alert(), it is much more readable and you won't have to confirm every alert.
After #mbuechmann pointing me to be able to see the actual error, I was able to determine that the issue I was having was actually to do with Wordpress. In order to use the Wordpress Ajax handler, you need to send an action to the REQUEST header. To do this, you need to send FormData, and without sending headers.
This code was found in this question : Custom Shortcode AJAX 400 Bad Request and enabled me to get my Fetch working with Wordpress.
var data = new FormData();
data.append( 'action', 'aj_ajax_demo' ); data.append( 'nonce', aj_ajax_demo.aj_demo_nonce );
fetch(aj_ajax_demo.ajax_url, {
method: 'POST',
body: data, }).then(response => {
if (response.ok) {
response.json().then(response => {
console.log(response);
});
} });

Not able to run simple nodejs server using express with ajax call at client side

I am trying to create simple NodeJS server using express framework.
and at client site, I wanted to fetch data using ajax call but it's not working
My Server side code
var express = require('express');
var app = express();
function sendJson(req, res){
console.log('User connected');
var jsonEx = '{ "result" :{"name" : "sachin", "surname" : "Tendulkar"}}';
res.type('application/json');
res.send(JSON.stringify(jsonEx));
}
app.use("/",express.static(__dirname));
app.get("/",sendJson);
app.listen(3000);
And client side code : which is the file index.html
$(document).ready(function(){
//Make ajax call to fetch data
$.ajax({
url: "http://localhost:3000/",
type: "GET",
dataType: 'json',
success: function(resp){
console.log(resp);
console.log("Hello");
}
});
});
but nothing happens after running the example.
console shows no data.
I enter below url in browser to run this
http://localhost:3000/index.html
what is problem with the code ?
Thank you,
Sachin
Express's app.use and app.get will act the same if you specify a path, but will resolve in order. So in this case, all your requests are rendering the index page. See this post(Routing with express.js - Cannot GET Error) Try changing the json data to another route like this:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
//Make ajax call to fetch data
$.ajax({
url: "http://localhost:3000/data",
type: "GET",
dataType: 'json',
success: function(resp){
console.log(resp);
console.log("Hello");
}
});
});
</script>
</head>
</html>
and
var express = require('express');
var app = express();
function sendJson(req, res){
console.log('User connected');
var jsonEx = '{ "result" :{"name" : "sachin", "surname" : "Tendulkar"}}';
res.type('application/json');
res.send(JSON.stringify(jsonEx));
}
app.use("/",express.static(__dirname));
app.get("/data",sendJson); // defining data as the get endpoint instead of root
app.listen(3000);

Resources