Getting a specific data from HTTP body response - ionic-framework

I am sending some data to my api by post and when it successfully submitted, it will return some data and I want to access the response data.
This is what I've got from my component :
this.http.post(this.restProvider.restApiUrl+'saveDraft', draftData, options)
.subscribe(data => {
console.log(data["_body"]);
}, error => {
console.log("Oooops!");
});
The console.log(data["_body"]); will resulting this data :
{"status":"ok","data_id":"2","statusMsg":"Saved as draft"}
What I'm trying to do now is to access the value of data_id but I'm not really sure how to get it inside my component. I thought it can be accessed by something like data["_body"]["data_id"]

I think data is an object. Try this:
console.log(data._body.data_id);
console.log(data["_body"].data_id);

Finally, I solved the issue by changing the console.log(data["_body"]); to console.log(data.json().data_id);
I refer to this discussion Angular 2: How to access an HTTP response body? and tried to apply the JSON and it works.

Related

Empty MultipartFile[] when sending files from Vue to SpringBoot controller

I'm doing a program that will help me to make monthly reports and I stuck at uploading photos which I need for one kind of the reports. For some reason, it doesn't get an array in the controller.
I use Springboot RestController at the backend and Vue with BootstrapVue and vue-resource on the other side.
index.html (BootstrapVue):
<b-form-file
v-model="photos"
accept="image/*"
multiple
placeholder="..."
></b-form-file>
<b-button #click="uploadPhotos">Upload</b-button>
inside vuemain.js:
data: {
photos: null,
},
methods: {
uploadPhotos(){
var formData = new FormData();
formData.append("photos", this.photos);
this.$http.post('reports/photo', formData).then(result => {
...
})
}, ...
inside Controller:
#PostMapping("/photo")
public void addPhoto(#RequestParam("photos") MultipartFile[] photo) {
System.out.println(photo.length); // shows 0
}
what I see inside Params at browser:
XHRPOSThttp://localhost:8080/reports-maker/reports/photo
[HTTP/1.1 500 326ms]
Request payload
-----------------------------4469196632041005505545240657
Content-Disposition: form-data; name="photos"
[object File],[object File],[object File],[object File]
-----------------------------4469196632041005505545240657--
​
So for some reason at this point #RequestParam("photos") MultipartFile[] photo it's empty array. But if I change it to just one photo like this: #RequestParam("photos") MultipartFile photo and send one from js: formData.append("photos", this.photos[0]); everything works nicely and photo gets uploaded to the server.
It's my first experience with Vue and to be honest I don't want to go deep into JS learning, so probably there is some silly mistake somewhere. Any way I can use a loop in JS method to upload them one by one, but that would be so ugly. I hope there is a better way to do it (without any additional JS libraries of course).
If you use axios then you should add header
var headers = {
'Content-Type': 'multipart/form-data',
};
axios.post(
'reports/photo',
formData,
{
headers: headers,
}
)
...
to be able send files to the server.
I agree, sending files in separate requests one by one is very "ugly", but I also don't like the idea of not using the mapping resources of Spring Boot, having to send all files with different names (seems disorganized) and having to work with MultipartHttpServletRequest, but there is a simple solution for this: Ian's answer to this question (not realy related to Vue.js, but useful) worked for me:
In order for Spring to map items in a request to a list, you need to provide the same name (in the FormData.append calls) for each item when appending to the form data. This allows Spring to effectively see the request as name=value1&name=value2&name=value3 (but obviously in the form of form data). When Spring sees the same key ("name") multiple times, it can map the values into a collection.
In your .vue file, append the photos with the same name:
for (let i = 0; i < this.photos.length; i++) {
formData.append("photos", this.photos[i]);
}
And in your Controller:
#PostMapping("/photo")
public void addPhoto(#RequestParam("photos") MultipartFile[] photo) {
System.out.println(photo.length); // Should be greater than 0 now
}
Note:
I used Vue Axios to consume my API and manually added the Content-Type: multipart/form-data header. Make sure its in your request header list.
I found an acceptable solution here https://stackoverflow.com/a/33921749/11508625 Rossi Robinsion's code works nicely. At least it looks better than sending files in separate requests one by one.
The answer is based on using getFileNames() which helps to iterate on files inside a request even if they are not in the array.

how to put param(body) in restangular?

I have api that required parameter in body, so I need to put that values in restangular, I have tried this
function deleteAccount(){
$log.log(accountIdDelete);
Restangular.one(apiDeleteAccount).customDELETE(
undefined,
[
{id : accountIdDelete},
{ContentType:'application/x-www-form-urlencoded'}
]).then(function(response){
$log.log(response);
var index = vm.account.indexOf(accountIdDelete);
if (index > -1) vm.account.splice(index, 1);
$('#deleteAccount').modal('hide');
});
}
What I'm trying is basicly tried to delete the data using id, I need that data Id put it in body request so that the api can detect select the data and delete it. but the code above that doesn't pass the value to the server? is there any way to put request body in restangular?
Based on my knowledge and searching on the internet, NgResource and restangular doesnt' support to set body into delete request, the only support for POST request to put data into the body, Correct me if I'm wrong but this is based on this answer :
https://stackoverflow.com/a/16203738/2652524

Ember js RESTAdapter PUT request adds .json to the end

I've been trying to learn Ember and I have a question.
In my store I'am getting data from .json like below. I have tried without buildUrl function but cant load the json file, then found this solution on SO.
CocktailApp.Store = DS.Store.extend({
revision: 12,
adapter: DS.RESTAdapter.extend({
bulkCommit: false,
url: "http://localhost:8888",
buildURL: function(record, suffix) {
var s = this._super(record, suffix);
return s + ".json";
}
})
});
Now comes my question: When I commit the chances (by pressing add to favs or remove from favs) RESTAdapter adds ".json" at the end of to PUT request. See the below code and screenshot
CocktailApp.CocktailController = Ember.ObjectController.extend({
addToFav: function () {
this.set('fav',true);
this.get('store').commit();
},
removeFromFav: function () {
this.set('fav',false);
this.get('store').commit();
}
});
I think thats why my PUT request can not be handled. But If I remove the builtURL function no json loaded at all. How can I resolve this problem?
Thanks
If the API endpoint url does not require .json at the end of it, then remove that line from your buildURL function. My guess is that the example code you got was consuming a ruby on rails api, or something similar.
remember, when you send a GET, PUT, POST, or DELETE to a url, that url needs to actually be a real endpoint. You can't just add extraneous stuff to it and have it still work.

Can we add Json object to RequestHeader of HTTP GET method

I am developing a new REST-full webservice for our application,I wanted to send the reqest data in requestHeader instead of sending as query param, as my request data is large.
I have My jquery code like below to add json to the request header and call the REST service GET method.
$.ajax({
beforeSend: function(req) {
req.setRequestHeader("test", "{name:mouli, id:918}");},
type : "GET",
data :'',
dataType : "jsonp",
url : 'http://localhost:29801/RestFulJSONExample/rest/jobdesc?callback=?',
success : function(data) {
alert("invoked");
}
});
});
And my GET method in my REST service is like
#GET
#Produces("application/javascript")
public JSONWithPadding getJobDescription(#Context HttpHeaders headers) {
List<String> requestHeader = headers.getRequestHeader("test");
//some logic here.
}
i could able to get the JSON object from the request header which i have added in the jquery request.
My question is ..
Can i follow this approach? is it secure and safe?
If not please tell me the other way?
What appears at the right side of the ":" in a header is mostly free. You have to take into account character set restriction in HTTP, and possible carriage returns in the JSON value (you know, headers of more than one line have a specific syntax). If your JSON examples are relatively simple, then I see no problem in that. It is just another way of organizing the actual value of a header line.

How to make ajax call in extjs and display the json value inside div?

I am new in extjs. I need to know how to make ajax call in extjs and display the json values in inside div. I don't need to use grid..
In ExtJS, you will have to use the Ext.Ajax class to make ajax calls to a remote server. Following is a typical code showing how to do it:
Ext.Ajax.request({
url: 'ajax_demo/sample.json',
success: function(response, opts) {
var obj = Ext.decode(response.responseText);
console.dir(obj);
},
failure: function(response, opts) {
console.log('server-side failure with status code ' + response.status);
}
});
In case of HTTP success (200 OK), the control will go inside the success callback and the first things that we have to do is decode the response.responseText which will give you the JSON response coming from the back-end data source.
Once you have code the JSON, you are free to format it and add it to any element (say to a div in your case). In case you want to format the JSON data nicely before adding, you may do that using Template/XTemplate.
I have used something like this.
$.getJSON('somepathtoserver/somefile.php?callback?', variable,function(res){
});
In the somefile.php, I have a callback function that processes and return the value to the js function.
like this:
{
echo $_GET['callback']. '(' . "{'someValue' : $calculatedVariable}" . ')';
}
This is tricky, but very useful when trying to ajax from one server to a different server, which is the reason I would use JSON here and not just a straight AJAX request.