On axios.get() request, response ONLY return the image header NOT image data? - axios

I`m writing tests in playwright where I check if all the images on my web page are valid.
I`m using Axios get request to get the image URL/path and because some of the images are quite big, I was thinking, one way to expedite tests, would be to only check the image header (image.size i.e.) and not even return the image data from Axios response, is this in any way possible with Axios or do I have to use another library for that?
await axios.all(allImagesURLs.map(imageURL => axios.get(imageURL))).then(axios.spread((...responses) => {
for (const response of responses) {
expect.soft(response.status).toBe(200)
}
})).catch(err => {
console.log(err)
});

I used axios.head() request, which only returns the response header and not the image data.

Related

Google Books API not returning the same as displayed on browser (Flutter)

I am building a book app with Flutter for Android and iOS. I am using Google Books API to retrieve book data, but I have noticed something strange which I dont understand. If we look at the book data displayed in chrome browser (https://www.googleapis.com/books/v1/volumes/b3GuDwAAQBAJ), we can see that the content (eg. field categories) is different than what I get when calling http response and printing out it's body. In addition to that, it also seems like unicode characters (eg. from description) are not sent.
The code that I'm using to get the API data can be seen below:
Response result = await http.get(Uri.parse(url), headers: {'content-type': 'application/json; charset=utf-8'});
if (result.statusCode == 200) {
final jsonResponse = jsonDecode(utf8.decode(result.bodyBytes));
if (jsonResponse["totalItems"] == 0) {
return List.empty();
}
//this prints out the content in above image
print(result.body.toString());
final booksMap = jsonResponse['items'];
List<dynamic> books = booksMap.map((i) => Book.fromJson(i)).toList();
return books;
It seems that https://www.googleapis.com/books/v1/volumes/b3GuDwAAQBAJ gives different data than your usual search query (eg. https://www.googleapis.com/books/v1/volumes?q=isbn:9780143123231). I do not know the reason why.
You can see the API response in raw form due to which unicode are present
Raw Form image from browser
but when you get api response you can parse into json, By parsing json that unicodes are removed and data is in proper format
if you use json Formatter extension in chrome you can see that the data in chrome in Json form and the response from api when you are hitting api by code are same.
Data in Json Form in Browser
in the application code , you set headers: {'content-type': 'application/json; thats why u received Json data code. and its not problem because you will use this data into your application,
you can see more content types here
Blockquote

Axios's response, what's in it??.....const response = await axios

I'm using Axios in WP e.g.
const response = await axios.delete(universityData.siteURL + "/wp-json/wp/v2/note/" + thisNote.getAttribute("data-noteID"))
All works fine but what I don't understand is the structure / content of 'response'. How do I interrogate 'response'? I had assumed for instance if I did console.log('Axios response: ' + response.data) I'd get a nicely laid out JSON like OO output in the Chrome console panel. But all I see is: Axios response: [object Object]
I can do this response.data.userNoteCount and I get something sensible back. BTW 'userNoteCount' is a field I added to my JSON for my custom post type. But how else do I see all the content of response without specifically having to target it?
Thanks to another contributor elsewhere this is the answer:
When you do the console.log you're adding the JSON object to the
string of Axios Response, so the JSON object is being converted to a
string, hence the object Object.
If you do it as two seperate lines, like
console.log('Axios Response');
console.log(response.data);
Then it will be outputted as the actual object.
With it being an HTTP Request though, rather than outputting it into
the console, what I'd do is open the Network tab of the browser
development tools, and select the XHR tab, and then the request will
appear in there and you can inspect the full response body there
without having to log it.

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.

Getting a specific data from HTTP body response

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.

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.