Return Body Text from Fetch API - promise

I would like to return the response body text returned by the POST that I send by fetch.
var r = '';
var res = fetch(this.commentsUrl, {
method: 'post',
body: JSON.stringify(comment),
headers: {
'Content-Type': 'application/json'
}
}).then(function (response) {
return response.text().then(function (text) {
r = text;
})
});
Neither r or res is returning the body text. They are both returning Promise. How do I only return the body text?

I was able to get the response body text by using await.
const response = await fetch(this.commentsUrl, {
method: 'post',
body: JSON.stringify(comment),
headers: {
'Content-Type': 'application/json'
}
});
const text = await response.text();

Related

Unable to upload pdf file in POST request using Cypress 6.4.0 & TypeScript

I am writing API tests using Cypress 6.4.0 & TypeScript where I need to upload a pdf file in the request body.
My code for the request is:
My code for the request body is:
public async createAssetDocTest() {
let url = sharedData.createAsset_url + sharedData.assetA;
let response = await fetch(url
,
{
method: 'POST',
body: await requestbody.createAssetDocBody(),
headers: {
Authorization: sharedData.bearer + " " + adminTokenValue,
Accept: sharedData.accept,
'Content-type': sharedData.docReqContent,
},
}
);
expect(response.status).to.equal(200);
public async createAssetDocBody(): Promise<any> {
const file = sharedData.doc;
cy.fixture(file).then((pdfDoc) => {
Cypress.Blob.binaryStringToBlob(
pdfDoc,
sharedData.contentTypeValue
).then(async (blob: string | Blob) => {
const formData = new FormData();
formData.set(sharedData.document, blob, file);
const body = {
formdata: {
document: {
value: pdfDoc,
options: {
filename: sharedData.document,
contentType: null,
},
},
},
};
return body;
});
});
}
However, the file does not upload the file & the request fails with error 400. Is there a better way to upload files in the body of the POST request?
enter image description here
Resolved this issue!
The main issue was that my Cypress version was too old. Upgraded to 9.7.0
Then added the following code:
public async createAssetDoc(): Promise<any> {
cy.fixture("pic location", "binary")
.then((file) => Cypress.Blob.binaryStringToBlob(file))
.then((blob) => {
var formdata = new FormData();
formdata.append("document", blob, "pic location");
const url = "your url";
cy.request({
url,
method: "POST",
body: formdata,
headers: {
Authorization:
"bearer" + " " + token,
Accept: "application/json",
"Content-Type": "multipart/form-data",
},
}).then((response) => {
expect(response.status).to.equal(201);
expect(response.statusText).to.equal(
sharedData.fileUploadStatusText
);
const finalResponse = String.fromCharCode.apply(
null,
new Uint8Array(response.body)
);
return finalResponse;
});
});
}

how to return server response from axios

I've looked at some of the other posts on this and it seems I need to apply 'await' I'm just not sure how to modify the following to do that
function sendData(url,emailPass){
let bodyFormData = new FormData()
for (const [key, value] of Object.entries(emailPass)) {
console.log(key,value)
bodyFormData.append(key,value)
}
axios({
method: 'POST',
url: url,
data: bodyFormData,
headers: {'Content-Type': 'multipart/form-data'}
})
.then(function (response){
return response.data
})
.catch(function(response){
return response
})
}
You should modify the function to return the promise from axios, which returns the response data.
function sendData(url,emailPass){
let bodyFormData = new FormData()
for (const [key, value] of Object.entries(emailPass)) {
console.log(key,value)
bodyFormData.append(key,value)
}
return axios({
method: 'POST',
url: url,
data: bodyFormData,
headers: {'Content-Type': 'multipart/form-data'}
})
.then(function (response){
return response.data
})
.catch(function(response){
return response
})
}
If you want to use async/await you can do
async function sendData(url,emailPass){
let bodyFormData = new FormData()
for (const [key, value] of Object.entries(emailPass)) {
console.log(key,value)
bodyFormData.append(key,value)
}
try{
const response = await axios({
method: 'POST',
url: url,
data: bodyFormData,
headers: {'Content-Type': 'multipart/form-data'}
});
return response.data;
}catch(e){
return e.response.data;
}
}

The recent update of yammer has degraded the message API

None of the parsed, plain, and rich items in the body returned by the message API no longer indicate the correct original text.
async function yammerApiFetch(url, postData, extendRequest) {
const yammerDefaultRequestHeader = {
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: 'include',
headers: {
'authorization': 'Bearer ' + options.accessToken,
'content-type': 'application/json'
},
mode: 'cors',
redirect: 'follow'
}
if (options.accessToken) {
yammerDefaultRequestHeader.headers.authorization = 'Bearer ' + options.accessToken;
} else {
delete yammerDefaultRequestHeader.headers.authorization;
}
let req = $.extend(yammerDefaultRequestHeader, extendRequest);
if (postData) {
req.method = req.method || "POST";
req.body = JSON.stringify(postData);
}
return (await fetch(url, req)).json();
}
bg.getMessage = async function (messageId) {
return await yammerApiFetch(
`https://www.yammer.com/api/v1/messages/${messageId}.json`);
};
If you write in the text of the comment, you will make a tag without escape.
Furthermore, if a string such as unknown.domain.com is included, an unusual tag such as is added.

authClient is not called with the AUTH_ERROR

I'm trying to implement custom rest client build on top of simple fetch.
If 401-403 response received, it must "redirect" app to login page.
According documentation, if 401-403 error received, it will magically calls authClient with the AUTH_ERROR, but it doesn't.
Can someone explain, how to connect it?
I'm trying to call rest client from component: It's simple reimplementation of 'simpleRestClient'
componentDidMount() {
restClient(CREATE, 'api/method', {
CurrentTime: new Date()
})
.then(o =>
{
this.setState({ Msg: Object.values(o.data.ServerTime) });
});
}
restclient implementation:
export const fetchJson = (url, options = {}) => {
const requestHeaders =
options.headers ||
new Headers({
Accept: 'application/json',
});
if (
!requestHeaders.has('Content-Type') &&
!(options && options.body && options.body instanceof FormData)
) {
requestHeaders.set('Content-Type', 'application/json');
}
if (options.user && options.user.authenticated && options.user.token) {
requestHeaders.set('Authorization', options.user.token);
}
return fetch(url, { ...options, headers: requestHeaders })
.then(response =>
response.text().then(text => ({
status: response.status,
statusText: response.statusText,
headers: response.headers,
body: text,
}))
)
.then(({ status, statusText, headers, body }) => {
if (status < 200 || status >= 300) {
return Promise.reject(
new HttpError(
(json && json.message) || statusText,
status,
json
)
);
}
let json;
try {
json = JSON.parse(body);
} catch (e) {
// not json, no big deal
}
return { status, headers, body, json };
});
};
const httpClient = (url, options = {}) => {
if (!options.headers) {
options.headers = new Headers({ Accept: 'application/json' });
}
return fetchJson(url, options);
}
Have you tried rejecting the promise with an Error rather than an HttpError?

post method not working phantomjs2

my header is
var headers = {
'Content-Type': 'application/json'
}
and data is
data = '{"mydata": "foo"}';
and code is
page.open('my site url', 'POST', data, headers, function (status) {
var jsonSource = page.content;
console.log(jsonSource);
phantom.exit();
});
but in onResourceRequest my method is 'GET'
what is problem ?

Resources