Parse.Cloud.httpRequest response gzip inflation / decompression - parse-platform

Is there something different in how Parse.Cloud.httpRequest is handling compression ?
On parse.com, I never had an issue with receiving a XML file, but using parse server on a different host (back4app), my httpResponse.text is a load of:
�E��ڇ�*q�������y���v^�����
Parse.Cloud.job("fetchData", function(request, status) {
Parse.Cloud.httpRequest({
method: 'GET',
url: 'http://example.com/test.xml',
headers: {
'Accept': 'application/xml',
'Accept-Encoding': 'gzip, deflate'
},
success: function (httpResponse) {
console.log("SUCCESS RECD FILE: " + httpResponse.text);
},
error: function (httpResponse) {
console.log('An error has occured with the http request.: ' + httpResponse);
}
});
}

Thanks for the great support at back4app, here is the solution
Basically, the option gzip:true is not documented anywhere but is needed.
I am not sure if the headers are needed, but I left them in anyway.
Parse.Cloud.httpRequest({
url: 'http://example.com/feed.xml',
headers: {
'Content-Type': 'application/xml',
'Accept-Encoding': 'gzip, deflate'
},
gzip:true,
success: function (httpResponse) {
...
},
error: function (httpResponse) {
...
}
}

Related

basic structure for converting ajax to axios?

Can some one give me example of how to convert ajax to axios ?
I am trying to convert this code into axios
$.ajax({
type: 'POST',
url: 'http://example.com/storeauthcode',
// Always include an `X-Requested-With` header in every AJAX request,
// to protect against CSRF attacks.
headers: {
'X-Requested-With': 'XMLHttpRequest'
},
contentType: 'application/octet-stream; charset=utf-8',
success: function(result) {
// Handle or verify the server response.
},
processData: false,
data: authResult['code']
});
axios.post('http://example.com/storeauthcode', authResult['code'], {
headers: {
'X-Requested-With': 'XMLHttpRequest'
'Content-Type: 'application/octet-stream; charset=utf-8',
},
transformResponse: (data) => { // do something with your data },
});
However a better place for the content-type would be the axios instance config itself.
Configure once globally:
axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
Then per request:
const result = await axios.post(
'http://example.com/storeauthcode',
authResult['code'],
{
headers: {
'Content-type': 'application/octet-stream; charset=utf-8'
}
}
);

Axios and fetch gives empty mapping in Golang even when url-encoded (header is added)

I'm using axios to send http requests ( i used fetch also but it gives the same result ).
axios.post("http://localhost:3000/login",
{
answer: 42
},
{
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
})
In my go file I'm logging the response
func post(req *http.Request, res http.ResponseWriter) {
req.ParseForm()
fmt.Println(req.Form)
}
The log is as follows :
map[{"answer":42}:[]]
However i want it to be as follows :
map["answer":[42]]
(I get such when i use postman)
What is the issue with this.
Outgoing data for reference
UPDATE
I used request ( built-in with nodejs) and also with jQuery ajax. Both of them work well.
Its just with axios and fetch which is not working
Here is the code :
request
The following code using nodejs request
var request = require("request");
var options = { method: 'POST',
url: 'http://localhost:3000/login',
headers:
{
'cache-control': 'no-cache',
'Content-Type': 'application/x-www-form-urlencoded' },
form: { answer: '42' } };
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});
jQuery ajax
The following is my jQuery code
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost:3000/login",
"method": "POST",
"headers": {
"Content-Type": "application/x-www-form-urlencoded",
"cache-control": "no-cache",
},
"data": {
"answer": "42"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
However, I am still unable to get axios and fetch to work. If someone finds it please update the answer
You need something like this:
var querystring = require('querystring');
axios.post('http://localhost:3000/login', querystring.stringify({'answer': 42},headers: {
'Content-Type': 'application/x-www-form-urlencoded'
});
You can set query string parameters using the params config option,
It will definitely works:
axios.post("http://localhost:3000/login", "", {
params: {answer: 42},
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
To find out more please read this https://github.com/axios/axios/issues/350#issuecomment-227270046

Passing from ajax to fetch on client side with a glassfish server

I have a phonegap application that uses
$.ajax(
type: 'POST,
dataType:"json",
url: 'test.com'
data: { mail: 'bob#test.com' }
)
which i get in my glassfish server doing something like
HttpServletRequest request;
request.getParameter('mail');
I'm moving my application in react native so i tryed
fetch('test.com', {
method: 'POST',
headers: {
'Content-Type': 'text/plain',
},
body: 'mail=bob#test.com',
})
and i tryed
fetch('test.com', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ mail: 'bob#test.com' }),
})
but neither of these worked, i'm deseperately having request.getParameter('mail') == null on server side.How can i do ?Note : i don't want to change the way the server handles things.

How do I pass an Image in the body of a OData Request in SAPUI5?

I need to pass an sap.m.Image file to the body(Data) of an OData request. Below is the code and I would like to know what to pass to the data parameter of the request so that my Image gets uploaded to the backend. When I pass the ImgValue which contains the dataurl it gives out an error saying
DOMException: Failed to execute 'createElementNS' on 'Document': The qualified name provided ('d:0') contains the invalid name-start character
OData.request({
requestUri: "http://ambrifiori.am.brothergroup.net:8081/sap/opu/odata/sap/ZPVSYSTEM_SRV/PromoImagesSet/",
method: "POST",
headers: {
"X-Requested-With": "XMLHttpRequest",
"Content-Type": "application/atom+xml",
"DataServiceVersion": "2.0",
/*"Accept": "application/atom+xml,application/atomsvc+xml,application/xml", */
"X-CSRF-Token": header_xcsrf_token,
"slug": "ajay122",
},
data: ImgValue,
});
I wasn't able to post image data through OData hence I used ajax...
This is what I did.
OData.request
({
requestUri: "http://AMBRIFIORI.am.brothergroup.net:8081/sap/opu/odata/sap/ZUI5_DAILY_SALES_SRV/DailySalesSet",
method: "GET",
headers:
{
"X-Requested-With": "XMLHttpRequest",
"Content-Type": "application/atom+xml",
"DataServiceVersion": "2.0",
"X-CSRF-Token":"Fetch" }
},
function (data, response)
{
header_xcsrf_token = response.headers['x-csrf-token'];
csrftoken = header_xcsrf_token;
$.ajax({
url: 'http://ambrifiori.am.brothergroup.net:8081/sap/opu/odata/sap/ZPVSYSTEM_SRV/PromoImagesSet/',
//dataType: 'json',
data: imgData,
//data: image,
type: 'POST',
headers: { "X-Requested-With": "XMLHttpRequest",
"Content-Type": "image/png",
"DataServiceVersion": "2.0",
/*"Accept": "application/atom+xml,application/atomsvc+xml,application/xml", */
"X-CSRF-Token": csrftoken,
"slug": slug,
},
success: function(data) {
debugger;
console.log(data);
},
error: function(data) {
debugger;
console.log(data);
}
});
My ImgData consists of image in Data URI format base64. I just added one statement in my Imgvalue to convert it to ImgData which is
var imgData = JSON.stringify(ImgValue);

How to write unit test to embeded ajax requests?

I have the handleDownload method which starts a file download. The function posts to the backend, which gives back a response, based on that a new request posts to the server where the files are. I saw that I can use mockjax to mock the requests, but how to handle the different paths like success, error, etc. How should I know which response triggers which path (success,error, complete, ...). What would be a great startegy to test the handleDownload function, and how? For mocking I use Sinon.js I don't have a really deep understanding yet. I should also check either the handleDownloadFinal function is called.
handleDownload: function(data, url) {
$.ajax({
type: "POST",
url: url,
data: {},
success: function(response) {
if (response.success) {
var start_token = response.token;
$.ajax({
type: start_token.method,
url: start_token.url,
beforeSend: function(xhr) {
xhr.setRequestHeader('Authorization', start_token.header);
},
success: function(start_response) {
handleDownloadFinal(start_response.status_token);
},
error: function(start_response) {
$.ajax({
type: "POST",
url: url + 'proxy/',
success: function(fallback_response) {
if (fallback_response.success) {
handleDownloadFinal(fallback_response.status_token, true, fallback_response.job_uuid);
} else {
errorDownload(response.error);
}
},
error: function(fallback_response) {
// Now this is some real error
generalErrorDownload();
},
dataType: 'json'
});
},
dataType: 'json',
xhrFields: {
withCredentials: true
}
});
} else {
errorDownload(response.error);
}
},
error: function(response) {
generalErrorDownload();
},
complete: function() {
},
dataType: "json"
});
}
You should use the fake server coming with sinon.
before(function(){
//create the server
this.server = sinon.fakeServer.create();
// let the server automatically respond for every request
server.autoRespond = true;
})
it('test something', function(){
//let the server respond for specific url with 200-ok
this.server.respondWith("POST", "/some/article/comments.json", [200, {
"Content-Type": "application/json"
}, '[{ "id": 12, "comment": "Hey there" }]']);
})
As you have a bunch of requests and you have to check all combinations I would suggest to have helper function for every request fail success so you could test the cases like this:
function letFirstRequestSucceed() {
this.server.respondWith("POST", "urlForFirstRequest", [200, {
"Content-Type": "application/json"
}, '[{ "id": 12, "comment": "Hey there" }]']);
}
function letSecondRequestFail() {
this.server.respondWith("POST", "urlForSecondRequest", [404, {
"Content-Type": "application/json"
}, '{error: "some error message"}');
}
function letThirdRequestFail() {
this.server.respondWith("POST", "urlForThirdRequest", [404, {
"Content-Type": "application/json"
}, '{error: "some error message"}');
}
it("should to something when the second and third request fails", function () {
sinon.spy(window, 'generalErrorDownload');
letFirstRequestSucceed();
letSecondRequestFail();
letThirdRequestFail();
handleDownload('someDate', 'aUrl');
expect(generalErrorDownload)
})
Btw you should think about to refactor you code using jquerys deferred which is supported by api ajax calls, this would make your could much more readable.

Resources