Ionic 2 http.post to login - http

I'm trying to convert an ionic app in an ionic 2 app and im strugle trying to remake the login progress.
I wrote this in my ionic 2 app:
loginUser(){
localStorage.setItem('username', this.username);
localStorage.setItem('password', this.password);
localStorage.setItem('company', this.company);
this.loginData = {};
this.loginData.UserID = this.username;
this.loginData.CompanyID = this.company;
this.loginData.Password = this.password;
let body = {"jsonLogin": JSON.stringify(this.loginData)}
let link = 'working link';
let headers = new Headers({
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
});
let options = new RequestOptions({headers: headers});
this.http
.post(link, body, options)
.map(res => res.json())
.subscribe(
data => {
console.log(data);
//this.navCtrl.push(MenuPage);
}, err => {
console.log(err);
});
}
While in the ionic 1 app this was the code:
$scope.loginUser = function () {
json = {};
json.UserID = $scope.data.username;
json.CompanyID = $scope.data.company;
json.Password = $scope.data.password;
$http({
method: 'POST',
data: {
"jsonLogin": JSON.stringify(json)
},
url: 'working link',
transformRequest: function (obj) {
var str = [];
for (var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
},
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
},
}
My problem is in the POST, when I post with my code of the ionic 2 app this is what my Form Data looks like:
{
"jsonLogin": "{\"UserID\":\"admin\",\"CompanyID\":\"test\",\"Password\":\"pass\"}"
}:
While the ionic 1 app Form Data looks like this:
jsonLogin:{"UserID":"admin","CompanyID":"test","Password":"pass"}
The POST is working since I got an error message from server, I just don't know how I can format the data to do a correct POST.
Thank you in advance for the help.
EDIT:
Got it working by added a new header:
let headers = new Headers({
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': '*/*'
});
And send a hardcoded string:
createStringForLogin(username: any, company: any, password: any){
return 'jsonLogin={"UserID":"'+username+'","CompanyID":"'+company+'","Password":"'+password+'"}';
}

I think
let body = {"jsonLogin": this.loginData};
should solve your problem. Let me know if it does not work.
Also, if you are having trouble in setting parameters to this.loginData. Set them like this:
this.loginData = {};
this.loginData['UserID'] = this.username;
this.loginData['CompanyID'] = this.company;
this.loginData['Password'] = this.password;

Related

Is there a way to get a callback from

I am downloading files to the client using Iron Router.
Router.route('zipfile', {
where: 'server',
path: '/zipfile/:name/:targetName',
action: function() {
var name = this.params.name;
var targetName = this.params.targetName;
var filename = `${ZIP_DIR}/${name}`;
var file = fs.readFileSync(filename);
var headers = {
'Content-type': 'application/zip',
'Content-disposition' : `attachment; filename=${targetName}.zip`,
};
this.response.writeHead(200, headers);
return this.response.end(file);
}
});
I wanted to know when the download has completed so I can then delete the source file on the server. Is there an easy way of doing that?
You could use the onAfterAction hook
Router.onAfterAction(function(req, res, next) {
// in here next() is equivalent to this.next();
}, {
only: ['zipfile'],
where: 'server
});

Recognize Text REST endpoint returns no results on success

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 :

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

Resources