The recent update of yammer has degraded the message API - yammer

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.

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 define a function 'server.remove' identical to 'server.revert'

How to define a function 'server.remove' (removing local files) identical to 'server.revert'.
'server.revert' send 'DELETE' request to '/api' with filename in request body.
I do not quite understand how the function should be organized, try something like that, but it does not work:
mounted() {
this.server = {
url: '/api',
remove: (source, load, error, revert) => {
revert(source);
error('oh my goodness');
load();
},
headers: {
Authorization: 'Bearer ' + this.token,
},
};
},
See here for the function signature, so something like this:
this.server = {
remove: (source, load, error) => {
const request = new XMLHttpRequest();
request.open('DELETE', 'url-to-api/' + source);
request.onload = function () {
if (request.status >= 200 && request.status < 300) {
load(request.responseText);
} else {
error('oh no');
}
};
request.send();
},
}

react axios 401 unauthorized and sometimes 403

I'm building a react native app post requesting laravel php api. it works on postman but not on Axios. Do you know how can i solve? I can't post a form data
I tried other forms sending post request of Axios. but none of them is solution
axios({
method: 'post',
url: 'URL',
params: {
"api_token": token,
"name": "talha"
},
headers: {
Accept: 'application/json',
'Content-Type': 'multipart/form-data'
}
}).then(response => alert(response)).catch(err => console.warn(err))
-----
const serverURL = "URL";
const http = axios.create({
timeout: 1000,
baseURL: serverURL,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
withCredentials: false,
cache: false,
dataType: "jsonp"
});
data is a formdata
await http.post("/passengers", data, config)
.then(Response => alert(Response.data))
.catch(error => console.warn("hata", error))
-----
axios.post( 'URL',
data,
{
headers: {
Accept: 'application/json',
'Content-Type': 'multipart/form-data'
}
}
).then(function(){
alert('SUCCESS!!');
})
.catch(function(){
alert('FAILURE!!');
});
postman script:
https://pastebin.ubuntu.com/p/vS54dytpCQ/
You can use my API helper function for batter development.
import axios from 'axios';
import AsyncStorage from '#react-native-community/async-storage';
const api = async (url, method, body) => {
/**
* config object for fetch
*/
const config = {
method: 'get',
baseURL: 'BASEURL WILL BE HERE',
url,
headers: {
'Content-type': 'application/json',
authorization: await AsyncStorage.getItem('auth_token'),
},
};
if (method) {
config.method = method;
}
if (body) {
config.data = body;
}
let response;
try {
response = await axios(config);
return {...response.data};
} catch (e) {
throw new Error(e.message);
}
};
export default api;
Then use this function
import api from 'filpath';
const functionName = async () => {
try{
const res = await api('/passengers', 'POST' posData);
console.log(res.data);
} catch(e){
alert('FAILURE!!')
}
}
Note: Save the auth token to AsyncStorage when user login.

Return Body Text from Fetch API

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();

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?

Resources