I need to send video from disk to Cognitive Services Emotion. I have almost done, but I was not capable to figure out how to format body properly and I can´t use '{url: http://...}' because I can´t expose the videos I want to submit. My code:
$.ajax({
"headers":{
"Content-Type":"application/octet-stream",
"Ocp-Apim-Subscription-Key":"SECRET"
},
type: "POST",
url: url,
"data": JSON.stringify({video: data}),
success: (x,stat,res) => {
},
error: (res) => {
}
});
As you can see I´ve tried to use 'octet-stream' to send the video. And that is one of many ways I did it. I don´t know if I need to send a JSON(similar when you send url) or do something else. I couldn´t find anything about it on official documentation. Help??
Thanks!
Please take a look at Sending binary data in javascript over HTTP.
$.ajax({
"headers":{
"Content-Type":"application/octet-stream",
"Ocp-Apim-Subscription-Key":"SECRET"
},
type: "POST",
url: url,
data: data,
success: (x,stat,res) => {
},
error: (res) => {
}
});
You want the body payload to be the raw (unencoded) binary data for Cognitive Services. The accepted formats are listed here.
One other important thing to remember is that jQuery calls the error handler for HTTP 202 responses, which is what you get from this API. So your error handler needs to handle that case, or, more to the point, your success handler won't ever be called.
Related
I am beginer in Cypress and looking for help with network stubbing.
My UI tiggers 3 API calls concurrently upon clicking on a button in the UI. All 3 API are of same endpoint, BUT each of them have different request and response.
I am able to stub the json response using cy.fixture, cy.server() and cy.route().
My need is to 'only stub the 3rd XHR call response', but, my test stubs all three because of the same endpoint.
Any suggessions on how could I test it using any condition ? example - Only stub the call if the parameters of 'request'XHR is 'XXX'?
I tried using before and after the .click() of submit button but that didn't work.
cy.fixture('myfixture').then(jsonresponse => {
function FixtureController(request, response) {
if (cy.url().request.body.contains("XXX")) {
cy.server()
cy.route('POST', 'URL', jsonresponse).as('myalias')
I appreciate any support.
Thanks!
You can use cy.intercept to match based on several things, including query parameters.
cy.intercept({
url: 'http://example.com/search*',
query: { q: 'expected terms' },
}, { fixture: 'myfixture' } )
If you need to match on the request body contents, you can use a route handler to specify.
cy.intercept('http://example.com/search*', (req) => {
if (req.body.contains('some string') {
req.reply({ statusCode: 200, fixture: 'myfixture' });
} else {
req.reply(); // not providing any input forwards the request as normal
}
});
Check out the cy.intercept documentation for more info.
I'm trying to upload a "binary file" from my cordova app into the imgur.com REST API using AngularJS.
But I'm not sure how I should format my request and what the "binary file" format is. From what I understand, a binary file is any thing that is not plain-text.
This is how I get file data from the local file system. It returns a blob instance. This part works fine.
var request = {
'url': 'file:///my/path/tmp/cdv_photo_025.png',
'options': {
'responseType': 'blob' // also tried 'arraybuffer', no diff.
}
}
var handler = function(response) {
window.myBlobData = response.data;
// handles the response
}
$http.get(request.url, request.options).then(handler);
Then later, I am using this to upload the blob to imgur, but this not working. I get a 400 (Bad Request). I am assuming the content-type, the disabling of the automatic encoding AngularJS does with transformRequest, and of course the binary data:
var request = {
'url': 'https://api.imgur.com/3/upload',
'options': {
'headers': {
'Authorization': 'Client-ID ***********',
'Content-Type': 'application/octet-stream',
},
'transformRequest': []
},
'data': {
'image': window.myBlobData, // a binary file
'type': 'image/png'
}
}
var handler = function(response) {
// handles the response
}
$http.post(request.url, request.data, request.options).then(handler);
For an image upload request with Imgur's API, you can't simply include the Client-ID in the header. If you were instead requesting public read-only information, then that would've been adequate.
If you haven't already, refer to the section on authorization in the Imgur API documentation.
Basically, you'll need to obtain an access token for the user for which you'll be uploading images on behalf of. As suggested by the documentation, you'll want to redirect or open a pop-up window to the below URL.
https://api.imgur.com/oauth2/authorize?client_id=YOUR_CLIENT_ID&response_type=access_token
Then, once you've obtained the access token, ensure your upload requests use it:
'Authorization': 'Bearer access_token'
Furthermore, simply use your blob data as the argument for the request (i.e. don't wrap it with the image and type properties).
I've been trying to make an React site, which would fetch a GET-response from API and print it out to my .html-file. I've managed to fetch the file just right, but i can't access the JSON-data server sends me.
If i use no-cors in my Fetch-request, i get an opaque response containing pretty much nothing, but if i go to Developer tools i can find my data there and read it. If i do use cors, almost same thing. I get an 403-error, but my data is in the browser memory, but my code doesn't print it out. I can find the response from Network in developer tools.
Why does the server give me an error, but still i get my data? And how can i access it, if it's in the browser?
class Clock extends React.Component {
constructor(props) {
super(props)
this.state = {data2: []}
this.apihaku = this.apihaku.bind(this)
}
componentDidMount() {
this.apihaku(),
console.log("Hei")
}
apihaku () {
fetch('https://#######/mapi/profile/',
{method: 'GET', mode:'no-cors', credentials: 'include',
headers: {Accept: 'application/json'}}
).then((response) => {
console.log(response);
response.json().then((data) =>{
console.log(data);
});
});
}
render() {
return <div>
<button>Button</button>
</div>
}}
ReactDOM.render(
<Clock />,
document.getElementById('content')
)
EDIT: Error images after trying out suggestions
https://i.stack.imgur.com/wp693.png
https://i.stack.imgur.com/07rSG.png
https://i.stack.imgur.com/XwZsR.png
You're getting an opaque response, because you're using fetch with mode: 'no-cors'. You need to use mode: 'cors' and the server needs to send the required CORS headers in order to access the response.
Fetch is doing exactly what the documentation says it's supposed to do, from Mozilla:
The fetch specification differs from jQuery.ajax() in two main ways:
The Promise returned from fetch() won’t reject on HTTP error status
even if the response is an HTTP 404 or 500. Instead, it will resolve
normally (with ok status set to false), and it will only reject on
network failure or if anything prevented the request from completing.
By default, fetch won't send or receive any cookies from the server,
resulting in unauthenticated requests if the site relies on
maintaining a user session (to send cookies, the credentials init
option must be set). Since Aug 25, 2017. The spec changed the default
credentials policy to same-origin. Firefox changed since 61.0b13.
So you need to use CORS, otherwise you get an opaque response (no JSON), and then 403 to me suggests that you haven't authenticated properly. Test your API with Postman, if I had to take a guess I'd say the API isn't sending the cookie because it's a GET request, so no matter how well you set your headers on the client it won't work. Try it as a POST instead. GET requests should really only be used to drop the initial HTML in the browser. I think for your headers use these, include the creds that the API sends and allow the domain to be different.
mode: "cors", // no-cors, cors, *same-origin *=default
credentials: "include", // *same-origin
Try this and see where is the error happening i believe in the parsing but lets check and see
fetch(https://#######/mapi/profile/, {
method: "GET",
headers: {
"Content-Type": "application/json"
},
credentials: "include"
})
.then((response) => {
console.log(response);
try {
JSON.parse(response)
}
catch(err){
console.log("parsing err ",err)
}
})
.catch((err)=>{
console.log("err ",err)
});
I had a similar issue, this kind of problem happend when a HTTP port try to send request to a HTTPS endpoint, adding a "mode:'no-cors'" doesn't do what is SOUND doing but rathere when the documentation says.
I fixed the issue by allowing in my API Application for calls from my HTTP port
(i'm using a .net 6 as an API in debugging mode, my code look like this https://stackoverflow.com/a/31942128/9570006)
WORK AROUND IS AT THE BOTTOM
Original problem
There are question like this all over the web and none of them really have answer for me. I can't get an http PATCH operation to work using angular to save my life. I've implemented $http, with shortcut $http.patch and without using the config object method:PATCH. I've used $resource by adding a custom method. And I've implemented Restangular using their patch and I'm getting the same error. I have the correct Content-Type as suggested in other posts. I think it's safe to say at this point, it's something I'm missing. I'm getting the same "404" message via postman when trying to patch. I can PUT, GET, POST, and DELETE, but not PATCH.
In the following images you can see that the resource exists for GET. But when trying to patch I get 404. Browsing to that endpoint shows the record. Which is stored in Mongodb.
Here's some code snippets:
Resangular GET:
var corporiumRecord = Restangular.one('corporium-mgmnts', $scope.uuid);
corporiumRecord.get().then(function(res) {
console.log(res)
}, function(err) {
console.log('Restangular failed: ', err)
});
Restangular Patch:
var data = {
corporiumId: $scope.newBlock
};
var corporiumRecord = Restangular.one('corporium-mgmnts', $scope.uuid);
corporiumRecord.patch(data).then(function(res) {
console.log(res)
}, function(err) {
console.log('Restangular failed: ', err)
});
$http attempt using config object:
controller code:
httpCorporiumSrv.updateCorporiumId('/corporium-mgmnts/' + $scope.params.id, data)
.then(handleUpdateSuccess)
.catch(handleUpdateError);
service code, tried forcing the content-type header but got same result
with or without it:
function updateCorporiumId(url, data) {
return $http({
method: 'PATCH',
url: url,
data: angular.toJson(data),
headers: {
'Content-Type': 'application/json;charset=utf-8'
}
//transformRequest: transformUpdateData
})
.then(handleUpdateSuccess)
.catch(handleUpdateErrors);
}
Using the .patch shortcut:
function updateCorporiumId(url, data) {
return $http.patch(url, data, {
transformRequest: transformUpdateData
})
.then(handleUpdateSuccess)
.catch(handleUpdateErrors);
}
Thing is I've tried this every which way I know how. I don't even know how to start debugging any more. I'm just getting 404 on a resource that does exist. Any suggestions on what might be happening to my request would be great.
Resolution:
For anyone having this issue, if you could post the fix or what's going on here to this point or PM me that would be awesome I'd like to know. I ended up just using PUT to fix this.
Quick Restangular solution:
Build the url template for findByOne like function using Restangular.one(url, _id) where '_id', is the id of the resource you're looking for. .get() goes out and finds that one resource by said id, which you can populate dynamically however you like. Once you have the one resource with GET copy it with Restangular.copy() which is different from angular.copy as it doesn't bind 'this' to the new object. Change what needs to be changed or added in the new object and then perform a .put() on it.
var corporiumRecord = Restangular.one('corporium-mgmnts', $scope.uuid);
corporiumRecord.get().then(function(res) {
var update = Restangular.copy(res);
// update date corporiumId
update.corporiumId = $scope.newBlock;
// submit new doc with altered value
update.put().then(function() {
console.log('updated')
});
console.log(update)
}, function(err) {
console.log('Restangular failed: ', err)
});
Also because mongo uses _id and Restangular uses id you have to add this to your module
angular.module('corporium-mgmnts').config(function(RestangularProvider) {
RestangularProvider.setMethodOverriders(['put', 'patch']);
// setRestangularFields is required for mongodb
RestangularProvider.setRestangularFields({
id: "_id"
});
});
I am trying to get the data from a JSONP proxy in sencha touch 2.3(I am using sencha architect 3 to develop). I was successfully able to place jsonp call and get the data back. But I am not getting how to separate every single element of json response. Here is my json Response:-
{"data":[{ "PLANTNUM": "1557", "ROUTEID": "90625", "DELIVERYDATE": "2014-02-12T00:00:00-06:00", "MESCOD": "15", "MESFCT": "DLV", "ORIGID": "HH", "JMSTIME": "02/11/2014 00:11:21", }],"success" : true}
Here is my function
success: function(response){
console.log(response);
var temp=response.data.PLANTNUM;
console.log(temp);
}
I can see below in my console:-
Here is my jsonP request
Ext.data.JsonP.request({
url: 'http://localhost:12608',
callbackKey: 'cbfn',
params: {
method: 'sapout',
type: 'sap',
ordnum: '1034986850'
}
I tried using response.PLANTNUM but that is also not working. It always shows undefined
Can anyone help me out here.
Thanks
data is an array, so you want response.data[0].PLATINUM.