Speech Service Authentication Issue on Bot Framework V4 - botframework

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>`

Related

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);
});
} });

Using Ajax in laravel and giving me unknown status. Why?

In my application i am using Ajax request but it is giving me jquery-3.3.1.js:9600 POST http://localhost:8000/get_types_ajax
gettin 419 (unknown status)
My javascript is:
$(document).ready(function() {
var ckbox = $("input[name='particulars']");
var chkId = '';
$("input[name='particulars']").on('change', function() {
if (ckbox.is(':checked')) {
values = [];
names = [];
$("input[name='particulars']:checked").each ( function() {
amount = $(this).val().split(",");
console.log("amount",amount);
values.push(amount[0]);
names.push(amount[1]);
});//checked
total_value = 0;
values.forEach(function(value) {
value = Number(value);
total_value = total_value + value;
document.getElementById('total').innerHTML = total_value;
});//foreach
}//if
else {
total_value = 0;
document.getElementById('total').innerHTML = total_value;
}
$.ajax({ url:"{{url('/get_types_ajax')}}",
type: 'POST',
data: {message:names},
success: function (data)
{
console.log(data);
}
});
});//onchange
});//ready
my web.php is :
Route::post('/get_types_ajax', 'DevkrutyaController#get_types');
The 419 error you are getting is due to the missing CSRF token in your ajax request. To pass a csrf token you can use ajax setup method of jquery
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': '{{ csrf_token() }}'
}
});
$.ajax({
url:"{{url('/get_types_ajax')}}",
type: 'POST',
data: {message:names},
success: function (data)
{
console.log(data);
}
});
});//onchange
});//ready
For more information https://laravel.com/docs/master/csrf#csrf-x-csrf-token
i see.You don't pass CSRF_TOKEN WITH Post Request
if your are using post method then u must pass CSRF_TOKEN with that other wise you can ignore(skip) some Url in VerifyCSRF token middleware
protected $except = [
'stripe/*',
];
other wise add this line in your js file it will automatically send
csrf token
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
for more detail read this article
Laravel uses CSRF token to protect your application from cross-site request forgery (CSRF) attacks. You will need to pass the CSRF token in your ajax.
In header
<meta name="csrf-token" content="{{ csrf_token() }}" />
In script
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
</script>

call server-side REST function from client-side

In the case, on the server side have some archive restApi.js with REST functions. My REST functions works fine, i test with Prompt Command.
In my client side have some archive index.ejs, And I want to call with this file.
My restApi.js: Server-side
var Client = require('./lib/node-rest-client').Client;
var client = new Client();
var dataLogin = {
data: { "userName":"xxxxx","password":"xxxxxxxxxx","platform":"xxxx" },
headers: { "Content-Type": "application/json" }
};
var numberOrigin = 350;
client.registerMethod("postMethod", "xxxxxxxxxxxxxxxxxx/services/login", "POST");
client.methods.postMethod(dataLogin, function (data, response) {
// parsed response body as js object
// console.log(data);
// raw response
if(Buffer.isBuffer(data)){
data = data.toString('utf8');
console.log(data);
re = /(sessionID: )([^,}]*)/g;
match = re.exec(data);
var sessionid = match[2]
console.log(sessionid);
openRequest(sessionid, numberOrigin); // execute fine
}
});
function openRequest(sessionid, numberOrigin){
numberOrigin+=1;
var dataRequest = {
data: {"sessionID":sessionid,"synchronize":false,"sourceRequest":{"numberOrigin":numberOrigin,"type":"R","description":"Test - DHC","userID":"xxxxxxxxxx","contact":{"name":"Sayuri Mizuguchi","phoneNumber":"xxxxxxxxxx","email":"xxxxxxxxxxxxxxxxxx","department":"IT Bimodal"},"contractID":"1","service":{"code":"504","name":"Deve","category":{"name":"Developers"}}} },
headers: { "Content-Type": "application/json" }
};
client.post("xxxxxxxxxxxxxxxxxxxxxxxxx/services/request/create", dataRequest, function (data, response) {
// parsed response body as js object
// console.log(data);
// raw response
console.log(data);
});
}
My index.ejs: Client side
<html>
<head> ------------- some codes
</head>
<meta ------- />
<body>
<script>
function send() {
$.ajax({
type: "POST",
url: "restApi.js",
data: '{ sendData: "ok" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
alert("successful!" + result.d);
}
});
}
</script>
<script src="restApi.js"></script>
</body>
</html>
I've try see others examples but does not work (Ajax).
And I need to know how to solved this, if have other Best practice for it, please let me knows.
In my console (Chrome) show if I call the ajax function:
SyntaxError: Unexpected token s in JSON at position 2 at JSON.parse (<anonymous>) at parse (C:\xxxxxxxxxxxxxxxxxxxxxxxxx\node_modules\body-parser\lib\types\json.js:88:17) at C:\xxxxxxxxxxxxxxxxxxxxxxxxx\node_modules\body-parser\lib\read.js:116:18
And if I click (BAD Request) show:
Obs.: Same error than app.js, but app.js works fine.
Cannot GET /restApi.js
In the case the file restApi.js Is a folder behind the index.
Folder:
Obs.: public folder have the index.ejs
Your problem is bad url. In case if you have fiule structure like this you have to point as shown in image
Based on the error I think the data you are posting via AJAX is not in correct syntax.
Change function send() as following.
function send() {
var obj = { "sendData" : "ok" };
$.ajax({
type: "POST",
url: "restApi.js",
data: obj,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
alert("successful!" + result.d);
}
});
}
This should resolve the error you are facing.
Try this now...
function send() {
var obj = {
sendData : "ok"
};
$.ajax({
type: "POST",
url: "Your url",
data: obj,
dataType: "json",
success: function (result) {
alert("successful!" + result.d);
},
error: function (error) {
console.log("error is", error); // let us know what error you wil get.
},
});
}
Your url is not pointing to js/restapi js.
and what code do you have in js/restapi js?
if your action page is app js you have to put it in url.
url:'js/restapi.js',

Dynamics CRM Web API Auth Error on Web Resource

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>

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