Wit.ai POST /speech wth HTTP requests - javascript

I try to record my voice and send it to /speech method on Wit.ai. So, from my browser, I collect a blob like this and want to execute an $.ajax() request :
recorder && recorder.exportWAV(function (blob) {
callback(blob);
// Ajax request here !
var data = new FormData();
data.append('file', blob);
$.ajax({
url : "https://api.wit.ai/speech?v=20171010",
headers: {
'X-Requested-With': 'JSONHttpRequest',
'Content-Type': 'audio/wav',
'Authorization' : 'Bearer OHROML6TAXxxxxxxxxxxxxSRYOVFCC'
},
type: 'POST',
data: data,
contentType: false,
processData: false,
success: function(data) {
alert(data);
},
error: function(error) {
alert("not so boa!"+JSON.stringify(error));
}
});
recorder.clear();
}, (AudioFormat || "audio/wav"));
All my results are a 400 error ! Bad request ! Or "Mismatch content type".
Any help would be appreciate here.
I tried without success :
recorder && recorder.exportWAV(function (blob) {
callback(blob);
$.ajax({
type: 'POST',
headers: {
'Authorization' : 'Bearer OHROML6TAEDFxxxx5W2SRYOVFCC'
},
url: 'https://api.wit.ai/speech?v=20171010',
data: blob,
contentType: 'audio/wav', // set accordingly
processData: false,
success: function(data) {
alert(data);
},
error: function(error) {
alert("not so boa!"+JSON.stringify(error));
}
});
// Clear the Recorder to start again !
recorder.clear();
}, (AudioFormat || "audio/wav"));
I have still the same issues :
Bad request or Wit doesn"t recognize the sample as a wav audio.

In the sample code you provided, you're submitting a request to Wit using FormData. Per the MDN Web Docs:
FormData uses the same format a form would use if the encoding type were set to multipart/form-data.
But in your request, you're specifying a Content-Type of audio/wav. So you're sending one type of data (multipart/form-data), but saying you're sending a different type (audio/wav).
Per the Wit API docs for POST /speech:
Body
Put your binary data (file or stream) in the body.
To send your audio as binary data, follow this answer to "How can javascript upload a blob?", which includes an example using jQuery.

Related

How to update outlook 2.0 API token using refresh-token?

I have next situation:
Main authentication flow happens on server, then client side obtains these data, since that moment I wanna client be able to update token by itself. It's seems there is all needed data on client(access_token, refresh_token), but I can't figure out how to organize request to https://login.microsoftonline.com/common/oauth2/v2.0/token route.
First I tried to get json response:
$.ajax({
url: `https://login.microsoftonline.com/common/oauth2/token?grant_type=refresh_token&refresh_token=refresh_token&scope=openid%20profile%20offline%20access%20user.read%20mail.read%20contacts.read%20calendars.read&client_id=client&client_secret=secret`,
type: 'POST',
cache: false,
processData: false,
contentType: false,
dataType: 'json',
headers: {
'Host': 'https://login.microsoftonline.com',
'Content-Type': 'application/json'
},
success: function(data) {
...
},
error: function(xhr) {
...
}
});
After that I figured out that it's only possible to get this data with redirect, is it correct? If it is, can someone produce an example of how to implement this, looks like it's needed to create an iframe and handle authorization somehow. Thanks.
UPDATED:
as Alina Li pointed in comment to her answer, there is a solution right in the official doc https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-auth-code-flow
According to my test, you could using refresh-token through the below code:
var data = "grant_type=refresh_token&refresh_token=refreshToken&client_id=" + appState.clientId;
$http = $http || $injector.get('$http');
$http.post(authUrl + '/token', data, {
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).success(function (response) {
}).error(function (err, status) {
});
You don’t need to add scope parameter.
Reference from:
Storing Refresh Token In JavaScript, Getting New Access Token

How to push a JSON to a webservice using Ajax

I have a form on my HTML page with some fields to be filled and an option to upload a file. My Javascript function converts the inputs to the fom into a json file. I am trying to push this generated json along with the file uploaded by the user to a webservice but I am getting an error which says
405 OPTIONS
Here's the Ajax function I wrote. The formData.serializeObject() function gives me the Json output to the form.
$(function() {
$('form').submit(function() {
($('#file')[0].files[0].name);
var formData = new FormData($("form")[0]);
formData.append("filename", $('#file')[0].files[0].name);
var obj = new FormData();
form = form
$.ajax({
url: "Webserviceurl:port/function_to_send_json",
type: "POST",
data: JSON.stringify(formData.serializeObject()),
dataType: "json",
contentType: "application/x-www-form-urlencoded;charset=UTF-8",
success: function(data) {
$.ajax({
url: "Webserviceurl:port/function_to_send_file",
type: "POST",
data: obj,
contentType: false,
success: function(data) {
},
error: function(data) {
console.log("Error Happened");
}
});
return false;
},
error: function(data) {
console.log("Error Happened");
}
});
})
});
What could I be doing wrong here?
The error message is being reported because you are making a preflighted request. This means the browser is sending an OPTIONS request asking for permission to make a POST request.
The server is responding to the OPTIONS request with a 405 error meaning "You can't make an OPTIONS request to this URL!"
That said …
data: JSON.stringify(…),
If you are sending JSON then you should say you are sending JSON, which ha a content type of application/json, not:
contentType: "application/x-www-form-urlencoded;charset=UTF-8",
There is no serializeObject method on formData objects, so formData.serializeObject() should be throwing an exception.
This question covers how to upload files with Ajax.

Javascript handling responses

I have a angularjs function which is calling a server side url and getting responses. This server side some times returning a xml response. sometimes returning a blog as the response. Can't predict. If I set the response type to "blob" in client side, it is showing image properly. But I cannot handle non blob responses because of xml responses also showing as a blob. Searched a lot in web about converting blob to xml(response containing a xml response). But couldn't find an answer :(
If I remove the response type: "blob", can handle the non blob response but cannot handle blob response.
Is there a way to handle both type of responses in a single method?
this is my angularjs code for getting response
$http({
url: apiConstants.BASE_URL + 'login',
method: "POST",
responseType: "blob",
data: {
"Req": req
},
headers: {
'X-Username': aUser,
'X-Password': aPass,
"Content-Type": "application/xml"
},
dataType: "xml"
}).success(function(data, status) {
console.log(data);
}
If you can manage to set the Content-Type header correctly in the response while serving your blob and xml responses from your server, then you can use the headers() in success callback to handle them accordingly.
$http.post(url, postData)
.then(function(response){
// success callback
var responseType = response.headers('Content-Type');
var actualType = responseType.split(';');
if(actualType[0] === 'application/xml'){
// handle XML files here
}else{
// handle blob files here
}
}, function(error){
// error callback
});
I solved this issue by doing following changes
$http({
url: apiConstants.BASE_URL + 'login',
method: "POST",
responseType: "blob",
data: {
"Req": req
},
headers: {
'X-Username': aUser,
'X-Password': aPass,
"Content-Type": "application/xml"
},
dataType: "xml"
}).success(function(data, status, headers, config) {
var responseType = headers('Content-Type');
if(responseType === 'application/xml;charset=utf-8'){
alert("xml");
}else{
alert("blob");
}
}

Using Dropbox v2 API from Browser

I'm trying to upload data to dropbox via webbrowser (FF 42.0, PhantomJS 1.9.8) and dropbox v2 api. My function looks like this
function(path, data, callback) {
$.ajax({
url: 'https://content.dropboxapi.com/2/files/upload',
type: 'post',
contentType: 'application/octet-stream',
beforeSend: function(jqXHR) {
jqXHR.setRequestHeader("Content-Type","application/octet-stream");
},
data: data,
headers: {
"Authorization": "Bearer " + token,
"Dropbox-API-Arg": '{"path": "' + path + ',"mode": "add","autorename": true,"mute": false}',
"Content-Type": "application/octet-stream"
},
success: function (data) {
callback(data);
}
});
}
Even I set the Content-Type at all attributes I can think of to application/octet-stream I get the following error
Error in call to API function "files/upload": Bad HTTP "Content-Type" header: "application/octet-stream
; charset=UTF-8". Expecting one of "application/octet-stream", "text/plain; charset=dropbox-cors-hack"
Taking a look at the request in Firebug shows me that the Content-Type was really set to application/octet-stream; charset=UTF-8. When trying text/plain; charset=dropbox-cors-hack as Content-Type the sent request has text/plain; charset=UTF-8, and I get the same error message.
How can I make jquery and my browser to set the headers I need.
EDIT: Same behavior in Chrome
IE works as expected
Technically, Firefox is just adhering to the W3C XMLHttpRequest spec:
http://www.w3.org/TR/XMLHttpRequest/#the-send()-method
Sending anything other than a Blob or ArrayBufferView can cause issues with browsers attempting to encode the data in UTF-8 (to follow the spec).
The right thing to do here is to avoid sending data as a String. Here are two examples of how to avoid this behavior:
// ... file selected from a file <input>
file = event.target.files[0];
$.ajax({
url: 'https://content.dropboxapi.com/2/files/upload',
type: 'post',
data: file,
processData: false,
contentType: 'application/octet-stream',
headers: {
"Authorization": "Bearer " + ACCESS_TOKEN,
"Dropbox-API-Arg": '{"path": "/test_ff_upload.txt","mode": "add","autorename": true,"mute": false}'
},
success: function (data) {
console.log(data);
}
})
Or, if you want to send up text, you can UTF-8 encode the text before uploading yourself. A modern way to do this is using TextEncoder:
var data = new TextEncoder("utf-8").encode("Test");
$.ajax({
url: 'https://content.dropboxapi.com/2/files/upload',
type: 'post',
data: data,
processData: false,
contentType: 'application/octet-stream',
headers: {
"Authorization": "Bearer " + ACCESS_TOKEN,
"Dropbox-API-Arg": '{"path": "/test_ff_upload.txt","mode": "add","autorename": true,"mute": false}'
},
success: function (data) {
console.log(data);
}
})
Try this...
private void upload(object sender, EventArgs e)
{
OAuthUtility.PutAsync
(
"https://content.dropboxapi.com/1/files_put/auto/",
new HttpParameterCollection
{
{"access_token",Properties.Settings.Default.AccessToken},
{ "path", Path.Combine(this.CurrentPath, Path.GetFileName(openFileDialog1.FileName)).Replace("\\", "/") },
{ "overwrite","false"},
{ "autorename","false"},
{openFileDialog1.OpenFile()}
},
callback : Upload_Result
);
}

"400 Bad Request" response for AJAX request

I have the following jQuery AJAX request:
// collect form data and create user obj
var user = new User();
user.firstname = $("#usrFirstName").val();
user.lastname = $("#usrSurname").val();
user.role = $("#usrRole").val();
// actual ajax request
$.ajax({
type: 'POST',
url : 'http://awesome-url',
crossDomain: true,
data: user,
contentType:"application/json; charset=utf-8",
dataType: 'json'
}).done(function(data, status) {
alert(JSON.stringify(data));
}).fail(function(data, status) {
alert(status);
alert(JSON.stringify(data));
});
The response from the Server is:
"status":400,"statusText":"Bad Request"
"The request sent by the client was syntactically incorrect."
The server is running Spring-MVC. But as far as I can tell it is working correctly. Because if I'm sending a request manually with Postman and the following configuration it works.
Header:
Content-Type application/json; charset=utf-8
Content:
{"firstname":"alex","lastname":"lala","role":"admin"}
I have to mention that it is a cross-domain request (for the time developing, it will be hosted on the same domain as the server later). I did disable the security settings in the browser and AJAX requests to the server are working fine (as long as I don't have to send data).
you need to serialize your json, try:
$.ajax({
type: 'POST',
url : 'http://awesome-url',
crossDomain: true,
data: JSON.stringify(user),
contentType:'application/json; charset=utf-8',
dataType: 'json'
})
JSON.stringify() method is used to turn a javascript object into json string. You need to have this. In addition it is better to include success and error portions in the AJAX.
$.ajax({
type: 'POST',
url : 'http://awesome-url',
crossDomain: true,
data: JSON.stringify(user), // turn a javascript object into json string
contentType:'application/json; charset=utf-8',
dataType: 'json',
success: function (html) {
alert(html);
}, error: function (error) {
alert(error);
}
})

Categories