Cypress - unable to store response.body data into a JSON file - cypress

I've created a POST XMLHttpRequest with FormData successfully. I now need to capture it's response body and get it stored in a JSON file.
Cypress.Commands.add(
"Post_Clients",
(imagePath, imageType, attr1, attr2, attr1Val, done) => {
cy.fixture(imagePath, "binary").then(imageBin => {
Cypress.Blob.binaryStringToBlob(imageBin, imageType).then(blob => {
const xhr = new XMLHttpRequest();
xhr.withCredentials = true;
const data = new FormData();
data.set(attr1, attr1Val);
data.set(attr2, blob);
xhr.open("POST", "https://api.teamapp.myhelpling.com/admin/clients");
xhr.responseType = "json"
xhr.setRequestHeader("accept", "application/json");
xhr.setRequestHeader("access-token", accesstoken);
xhr.setRequestHeader("client", client);
xhr.setRequestHeader("expiry", expiry);
xhr.setRequestHeader("token-type", tokentype);
xhr.setRequestHeader("uid", uid);
xhr.onload = function() {
done(xhr);
};
xhr.onerror = function() {
done(xhr);
};
xhr.send(data);
});
});
}
);
it.only("API POSTing TEST", () => {
cy.Post_Clients(
"/images/clients/Golden JPEG.jpeg",
"image/jpeg",
"client[name]",
"client[client_logo_attributes][content]",
"Test Attr 1 Value is Hi!!!",
resp => {
cy.writeFile(
"cypress/fixtures/POST API OUTPUT DATA/Client.json",
resp.response
);
expect(response.status).to.eq(201);
}
);
});
Kindly note that expect(response.status).to.eq(201); assertion works well.
Following code logs the body properly in the console
cy.log("Response Body", resp.response);
console.log("Response Body", resp.response);
Response Body is: -
{"client":{"id":452,"name":"Test Attr 1 Value is Hi!!!","client_logo":{"id":543,"path":"https://api.teamapp.myhelpling.com/uploads/client_images/6279486665-1551780183.","thumb":"https://api.teamapp.myhelpling.com/uploads/client_images/thumb_6279486665-1551780183.","medium":"https://api.teamapp.myhelpling.com/uploads/client_images/medium_6279486665-1551780183.","large":"https://api.teamapp.myhelpling.com/uploads/client_images/medium_6279486665-1551780183.","filename":"blob","ratio":1.78}}}
but
cy.writeFile(
"cypress/fixtures/POST API OUTPUT DATA/Client.json",resp.response
);
doesn't save the response body in Client.JSON file.
cy.writeFile seems to not work in this code. I've verified this by
passing a JSON e.g. {"A":"B"} and that too didn't make it to the
JSON.

Thanks everyone for all you kind help. I've made it work by calling cy.writeFile inside onLoad event before triggering XHR request. Here's the code sample with some other updates that I've made for my other works: -
Cypress.Commands.add(
"Post_Bucket",
(imagePath, imageType, title, img, titleVal) => {
cy.fixture(imagePath, "binary").then(imageBin => {
Cypress.Blob.binaryStringToBlob(imageBin, imageType).then(blob => {
const xhr = new XMLHttpRequest();
const data = new FormData();
data.set(title, titleVal);
data.set(img, blob);
cy.readFile(Cypress.env("IDStore")).then(obj => {
xhr.open(
"POST",
Cypress.env("BucketPostURLPart1") +
obj.journeyID +
Cypress.env("BucketPostURLPart2"),
false
);
xhr.setRequestHeader("accept", "application/json");
xhr.setRequestHeader("access-token", accesstoken);
xhr.setRequestHeader("client", client);
xhr.setRequestHeader("expiry", expiry);
xhr.setRequestHeader("token-type", tokentype);
xhr.setRequestHeader("uid", uid);
xhr.onload = function() {
if (this.status === 201) {
cy.writeFile(
Cypress.env("BucketOutputFile"),
JSON.parse(this.responseText)
);
cy.readFile(Cypress.env("IDStore")).then(obj => {
obj.bucketID = JSON.parse(this.responseText).bucket.id;
cy.writeFile(Cypress.env("IDStore"), obj);
});
}
};
xhr.send(data);
});
});
});
}
);

This is the simple example try with this one.
cy.request('https://jsonplaceholder.cypress.io/users')
.then((response) => {
cy.writeFile('cypress/fixtures/users.json', response.body)
})

Related

FormData not being read by laravel on backend

This qn is related to vue and alravel, I try to make and api request on vue with const response = await http.put("api/v1/vehicles/" + vehicleId,formData);. I see the data going on payload, But when i DO dd($request->all()) It shows empty
async update(vehicleId, data) {
try {
let formData = new FormData();
(data.files ?? []).forEach((file, key) => {
formData.append("files[]", file);
});
Object.entries(data).forEach(([key, value]) => {
if (key !== "files" && value !== null) formData.append(key, value);
});
const response = await http.put(
"api/v1/vehicles/" + vehicleId,
formData
);
return Promise.resolve(response.formData);
} catch (err) {
return Promise.reject(err);
}
},
When I hit url with const response = await http.put("api/v1/vehicles/" + vehicleId,data); It shows on $request->all(). I need to add formData to attach the fiels. Is it because put request doesnot read formData??
I saw a method spoofing and I did this
let vehicle_data = { _method: "PUT", form: formData };
const response = await http.post(
"api/v1/vehicles/" + vehicleId,
vehicle_data
);
BUt it gives null on form?
PUT and PATCH request types require adding a _method property in payload and using .post instead .put
Said that, you should do this:
async update(vehicleId, data) {
try {
let formData = new FormData();
(data.files ?? []).forEach((file, key) => {
formData.append("files[]", file);
});
Object.entries(data).forEach(([key, value]) => {
if (key !== "files" && value !== null) formData.append(key, value);
});
formData.append("_method", "PUT")
const response = await http.post(
"api/v1/vehicles/" + vehicleId,
formData
);
return Promise.resolve(response.formData);
} catch (err) {
return Promise.reject(err);
}
},
Please note that I've changed request to http.post() and added formData.append("_method", "PUT")
Your API will recognize it as a PUT request and also grab payload correctly.
The same should be done for PATCH requests.

Failed to execute 'fetch' on 'Window': Invalid name

simple website contact submit code using fetch sending formdata to api.
the fetch method returns'Failed to execute 'fetch' on 'Window': Invalid name' error in console, meanwhile XMLHttpRequest works.
How can i fix the fetch method?
contactForm.addEventListener('submit', async function (e) {
e.preventDefault();
// console.log('clicked');
const formData = {
name: formName.value,
email: formEmail.value,
tel: formTel.value,
message: formMessage.value,
};
// FIXME
try {
const response = await fetch('/', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(formData),
});
return response.json();
} catch (err) {
console.log(err.message);
}
// XMLHttp methode works
// let xhr = new XMLHttpRequest();
// xhr.open('POST', '/');
// xhr.setRequestHeader('Content-Type', 'application/json');
// xhr.onload = function () {
// if (xhr.responseText === 'success') {
// //add a popout window
// formName.value = '';
// formEmail.value = '';
// formTel.value = '';
// message.value = '';
// } else {
// alert('Something went wrong!');
// }
// };
// xhr.send(JSON.stringify(formData));
});

Network Request failed while sending image to server with react native

i want to send image to a server and getting the result with a json format but the application returns a Network Request failed error
react native 0.6 using genymotion as emulator
i tried RNFetchblob but the result take a long time to get response (5 min )
also i tried axios but it response with empty data with 200 ok
this is the function that import the image
OnClick = () => {
ImagePicker.showImagePicker(options, response => {
console.log("Response = ", response);
if (response.didCancel) {
console.log("User cancelled image picker");
} else if (response.error) {
console.log("Image Picker Error: ", response.error);
} else {
let source = { uri: response.uri };
// You can also display the image using data:
//let source = { uri: 'data:image/jpeg;base64,' + response.data };
this.setState({
avatarSource: source,
data: response.data,
BtnDisabled: false
});
console.log();
}
});
};
and this method that sends the image
Send = async () => {
let url = "http://web001.XXX.com:8000/api/prediction/check_prediction/";
let UplodedFile = new FormData();
UplodedFile.append('file',{ type:'image/jpeg', uri : this.state.avatarSource , name:'file.jpeg'});
fetch(url, {
method: 'POST',
body:UplodedFile
})
.then(response => response.json())
.then(response => {
console.log("success");
console.log(response);
})
.catch(error => {
console.error(error);
});
i expect json format
ScreenShot here
can you change your code like this?
OnClick = () => {
ImagePicker.showImagePicker(options, response => {
console.log("Response = ", response);
if (response.didCancel) {
console.log("User cancelled image picker");
} else if (response.error) {
console.log("Image Picker Error: ", response.error);
} else {
let source = { uri: response.uri };
// You can also display the image using data:
//let source = { uri: 'data:image/jpeg;base64,' + response.data };
this.setState({
pickerResponse: response,
data: response.data,
BtnDisabled: false
});
console.log();
}
});
};
Send = async () => {
let url = "http://web001.XXX.com:8000/api/prediction/check_prediction/";
let UplodedFile = new FormData();
UplodedFile.append('file',{ type:'image/jpeg', uri : this.state.pickerResponse.path , name:'file.jpeg'});
axios({
method: "post",
url: url,
data: UplodedFile
})
.then(response => {
console.log("success");
console.log(response);
})
.catch(error => {
console.error(error);
});

Worpress bad request 400 pure Javascript

I get this following error when I use ajax in pure javascript:
"POST http://localhost:8888/website/wp-admin/admin-ajax.php" 400 (Bad Request) line in code: this.xhr.send(JSON.stringify(data));
my Contact.js file:
var Contact = function(data){
//setups and others methods
this.onFormSent = function(data){
data = {
action: 'my_action',
data: data
};
if(this.ajaxSendURL !== null){
this.xhr.open("post", this.ajaxSendURL);
this.xhr.setRequestHeader("Content-Type", "application/json");
this.xhr.onload = function() {
if(self.xhr.status === 200){
console.log(self.xhr.responseText);
var response = JSON.parse(self.xhr.responseText);
self.onSuccessForm(data);
}
};
this.xhr.send(JSON.stringify(data));
}
};
};
I use a form tag in html after filled my "form" and pressed the submit button it should call 'my_action' in php.
this my function.php:
function add_theme_scripts() {
wp_enqueue_script('Contact', get_template_directory_uri() . '/js/Contact.js', array(), 1.0, true);
wp_localize_script('Contact', 'ajaxurl', admin_url('admin-ajax.php'));
}
add_action('wp_enqueue_scripts', 'add_theme_scripts');
/* AJAX */
add_action('wp_ajax_my_action', 'my_action');
add_action('wp_ajax_nopriv_my_action', 'my_action');
function my_action(){
echo 'msg from server:' + $_POST['data']['name'];
die();
}
What am I doing wrong?
Updated: replaced by the following code and it works
this.onFormSent = function(data){
data = "action=my_function&name=" + dada.name;
this.xhr.setRequestHeader("Content-Type", "application/json");
...
}
Change this lines in ajax request;
data = {
action: 'my_action',
data: youdatadata
};
var data = $.param(data);
http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
http.send(data);

Observable not firing during Angular 2 HTTP request

I have the following method, using Ionic 2 with Angular 2:
private login(params: any, url: string){
var p = new Promise<JsonResult>((resolve, reject) => {
let body = JSON.stringify(params);
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
this.http.post(url, body, options)
.timeout(10000, new Error('Timeout exceeded during login'))
.subscribe((res) => {
let json = new JsonResult().deserialize(res.json());
resolve(json);
}, (err) => {
reject(err);
});
});
return p;
}
No matter what I do, the subscribe is not working as expected.
The error handler never gets fired. Not even after the timeout has exceeded.
Is this a known problem, or is there something wrong with my syntax?
Any help would be appreciated.
If you want to return a Promise I would do it this way:
private login(params: any, url: string){
let body = JSON.stringify(params);
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this.http.post(url, body, options)
.timeout(10000, new Error('Timeout exceeded during login'))
.catch(err => {
console.log(err);
return Observable.of([]));
})
.map((res) => {
return new JsonResult().deserialize(res.json());
})
.toPromise();
}

Resources