Recognize Text REST endpoint returns no results on success - microsoft-cognitive

I'm using the recognizeText REST endpoint from javascript running locally on my dev machine. I can successfully call the endpoint, get the operation-location url for the result and send a GET request to that url.
The issue is the return from the operation-location url is 200 success (meaning the operation has completed and doesn't need more time), but the body of the result is always empty.
How can I get the extracted text from the response?
My code:
var subscriptionKey: string = "my key";
var endpoint: string = "https://eastus.api.cognitive.microsoft.com/";
var uriBase: string = endpoint + "/vision/v2.0/recognizeText?mode=Printed";
const fetchData = {
headers: {
"Content-Type": "application/json",
"Ocp-Apim-Subscription-Key": subscriptionKey
},
body:
'{"url": "https://www.bing.com/th/id/OIP.nZoyhANat4WNndv0jeoXFAHaLp?w=183&h=289&c=7&o=5&dpr=1.5&pid=1.7"}',
method: "POST"
};
fetch(uriBase, fetchData).then(data => {
var operationLocation = data.headers.get("Operation-Location");
if (operationLocation) {
const resultFetchData = {
headers: {
"Content-Type": "application/json",
"Ocp-Apim-Subscription-Key": subscriptionKey
},
method: "GET"
};
setTimeout(function(operationLocation, resultFetchData) {
fetch(operationLocation, resultFetchData).then(resultData => {
alert(JSON.stringify(resultData, null, 2));
});
}, 10000);
}
});
}

There is something wrong with your fetch request code block, try this :
fetch(uriBase, fetchData).then(data => {
var operationLocation = data.headers.get("Operation-Location");
if (operationLocation) {
const resultFetchData = {
headers: {
"Content-Type": "application/json",
"Ocp-Apim-Subscription-Key": subscriptionKey
},
method: "GET"
};
setTimeout(()=> {
fetch(operationLocation, resultFetchData).then(resultData => {
return resultData.json();
}).then((data)=>{
console.log(JSON.stringify(data, null, 2));
});
},10000);}
});
Result :

Related

How to pass params with body in flutter http put method

Hi i am trying to pass the query prams to http put method.
Here i am trying in this way
var queryParameters = {
'id': '285',
};
return http.put(
'http://domainname${queryParameters}', body: json.encode(formData)
,
headers: {
'Authorization': receivedToken,
'X-Oc-Store-Id': receivedstoreid,
},
try this,
var body = jsonEncode({
"email": "${emailController.text}",
"password": "${passwordController.text}"
});
.
var response = await http.put("http://domainname + /${id}", body: body, headers: {
'Authorization': receivedToken,
'X-Oc-Store-Id': receivedstoreid,
}).timeout(Duration(seconds: 30));

How to post multipart/formdata using fetch in react-native?

i want to post Form Data like that.
what should i prepare for sending image file data?
i have Uri, type, filename, size.
then will use fetch for it.
Content-type in header is 'multipart/formdata'
thanks for helping
You should have an upload function, which should look like this:
upload(url, data) {
let options = {
headers: {
'Content-Type': 'multipart/form-data'
},
method: 'POST'
};
options.body = new FormData();
for (let key in data) {
options.body.append(key, data[key]);
}
return fetch(requestUrl, options)
.then(response => {
return response.json()
.then(responseJson => {
//You put some checks here
return responseJson;
});
});
}
And you call it this way, sending the image blob path:
this.upload('http://exampleurl.com/someApiCall', {
file: {
uri: image.path,
type: image.mime,
name: image.name,
}
}).then(r => {
//do something with `r`
});
You need to create an instance of FormData and pass that as the body to fetch, like so:
const data = new FormData()
data.append("something", something)
fetch(url, { method: 'POST', body: form })
React Native code
fetch("url" ,{
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
method:'POST',
body: JSON.stringify(this.state.imageholder)
}).catch(function(error) {
console.log('There has been a problem with your fetch operation: ' + error.message);
throw error;
});
Spring boot code
#PostMapping(value="/",consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<?> saveCustomerOrder(#RequestBody String[] file) throws SerialException, SQLException {
TestImg imgObj=null;
for (String img : file) {
imgObj=new TestImg();
byte[] decodedByte = Base64.getDecoder().decode(img);
Blob b = new SerialBlob(decodedByte);
imgObj.setImg(b);
testRepo.save(imgObj);
}

Confused on creating an update request for DynamoDB using API Gateway

I'm writing a lambda function to get the resources by posting the phone number. below is my code.
exports.handle = function (e, ctx, cb) {
var body = JSON.parse(e.body);
var params = {
TableName: 'userAddresses',
FilterExpression: '#phone = :phone',
ExpressionAttributeNames: {
"#phone": "phone"
},
ExpressionAttributeValues: {
":phone": body.phone
}
}
dynamodb.scan(params).promise().then(function (data) {
var uw = data.Items[0];
var res = {
"statusCode": 200,
"headers": {},
"body": JSON.stringify(uw)
};
ctx.succeed(res);
});
}
this is working fine. but I want to do the same with put and patch. Can some one please point me in a right direction.
for patch, it should be something like, the phone should be passed as a queryParameter and the body to be updated in just json body
Thanks
Is the phone number a hash key? If so, use dynamodb.get() or dynamodb.query() instead...
Here's a quick and dirty example, it may help you to get started with DynamoDB updates:
const AWS = require('aws-sdk);
const bluebird = require('bluebird');
AWS.config.setPromisesDependency(bluebird);
const dynamodb = new AWS.DynamoDB.DocumentClient();
let update = (id, attributes) => {
var params = {
TableName: 'MyTableName',
Key: {
myHashKeyAttr: id
},
AttributeUpdates: attributes
};
return dynamodb.update(params).promise();
};
exports.handler = (event, context, callback) => {
console.log(JSON.stringify(event, null, 2));
let body = JSON.parse(event.body);
let attributes = {
firstName: {
Action: 'PUT',
Value: body.firstName
},
lastName: {
Action: 'PUT',
Value: body.lastName
},
updatedAt: {
Action: 'PUT',
Value: new Date()
}
};
// only if the phone number is a hash key...
update(event.queryStringParameters.phone, attributes)
.then(
(result) => {
console.log(result);
callback({
statusCode: 200,
headers: {},
body: JSON.stringify({message: 'updated!'})
});
}
).catch(
(error) => {
console.error(error);
callback({
statusCode: 500,
headers: {},
body: JSON.stringify({message: 'ops!'})
});
}
);
}

How to pass two objects to web api?

Here is my WebAPI POST method which expects BookingDetail and BookingVenue objects:
[HttpPost]
[ValidateUserSession]
public JsonResult CheckBooking(BookingDetail BookingDetail, BookingVenue objBV)
{
try
{
if (BookingDetail != null && objBV != null)
{
bool result = Ibook.checkBookingAvailability(BookingDetail, objBV);
if (result == false)
{
return Json("NotAvailable");
}
else
{
return Json("Available");
}
}
else
{
return Json("Available");
}
}
}
Angular code from where I'm getting the values from UI and making a post passing these 2 objects:
this.checkbookingavailability = function (Book) {
var BookingVenueObj = {
EventTypeID: Book.EventSelected,
VenueID: Book.Venueselected,
GuestCount: Book.NoofGuest,
};
var BookingDetailObj = {
BookingDate: Book.BookingDate
};
var response =
$http({
method: "POST",
url: "/Booking/CheckBooking/",
headers: {
'RequestVerificationToken': $cookies.get('EventChannel')
},
data: { BookingDetail: BookingDetailObj, BookingVenue: BookingVenueObj }
});
return response;
}
Problem is in my WebAPI code, both the objects as null
You can only pass one object in the body so I would recommend you to create a new DTO "BookingDto" for that containing BookingDetail and BookingVenue as member and change the signature of your WebAPI to this:
[HttpPost]
[ValidateUserSession]
public JsonResult CheckBooking([FromBody]BookingDto bookingObj)
You need to serialize JSON object which you are sending to server just by calling JSON.stringify over object.
var response =
$http({
method: "POST",
url: "/Booking/CheckBooking/",
headers: {
'RequestVerificationToken': $cookies.get('EventChannel')
},
data: JSON.stringify({
BookingDetail: BookingDetailObj,
BookingVenue: BookingVenueObj
})
});
return response;
As dear Pankaj mentioned you need to Serialize your data objects with Stringify function in javascript, Also consider that you must mention that this http request contain Application/JSON content. All these can be shown here:
var response =
$http({
method: "POST",
url: "/Booking/CheckBooking/",
headers: {
'RequestVerificationToken': $cookies.get('EventChannel'),
'Content-Type' : 'application/json'
},
data: JSON.stringify({
BookingDetail: BookingDetailObj,
BookingVenue: BookingVenueObj
})
});
return response;

How to response from servlet to YUI?

I send io to server with YUI and how to respond back to YUI?
Here is code :
var user = {
userName: username,
password: password,
customerId: customerId
};
var success = function (ioId, o) {
responseContent = Y.JSON.parse(o.responseText);
if (responseContent.code == 0) {
window.location = 'Home.jsp';
}
};
var failure = function (ioId, o) {
//do something
};
var cfg = {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
sync: false,
data: user,
on: {
'success': success,
'failure': failure
}
};
new Y.IO().send("http://localhost:7778/web/LoginController", cfg);
Redirect not work and i decide to redirect by YUI. Thanks!!!
var success = function (ioId, o) {
responseContent = Y.JSON.parse(o.responseText);
if (responseContent.code == 0) {
window.location = 'Home.jsp';
}
//Like this?
responseDiv.innerHTML = responseContent.yourData;
};

Resources