I am trying to fetch blob data (image) back to client using redux toolkit but I am not getting it.
**THIS IS MY CONTROLLER FILE**
const getProfilePicture = async (req, res) => {
try {
const base64Data = await ProfilePic.findByPk(req.user.id);
res.send(base64Data);
}catch(error) {
res.status(500).send("error.message")
}
};
and when I hit the route on postman, I get the response below. which I do not know if it is the right response I am to get
{
"id": "6dc38579-4e0f-4d4b-8777-7b6527408e72",
"avatar": {
"type": "Buffer",
"data": [
91,
111,
98,
106,
101,
99,
116,
32,
79,
98,
106,
101,
99,
116,
93
]
},
"description": null,
"createdAt": "2023-02-17T09:22:28.000Z",
"updatedAt": "2023-02-17T09:28:00.000Z"
}
below if the file for making the API call
const getProfilePicture = async (req, res, token) => {
const config = {
headers: {
Authorization: `Bearer ${token}`,
},
};
try {
await axios
.get(API_URL + "getProfilePicture", config, {
responseType: "blob",
responseEncoding: "base64",
})
.then((response) => {
Buffer.from(response.data, "binary").toString("base64");
});
} catch (error) {
res.status(500).send("There is an error here");
}
};
please help me see what I am getting wrong here.
Thanks.
const getProfilePicture = async (token) => {
const config = {
headers: {
Authorization: `Bearer ${token}`,
},
responseType: "arraybuffer",
};
try {
const response = await axios.get(API_URL + "getProfilePicture", config);
const imageBuffer = Buffer.from(response.data, "binary");
const imageBlob = new Blob([imageBuffer], { type: "image/png" }); // Replace image/png with the actual MIME type of your image
return URL.createObjectURL(imageBlob);
} catch (error) {
console.error(error);
throw error;
}
};
Related
This issue only occurs with posts with multipart video, Posts with images and videos below 4MB are working, when posting to Posts API i get a response with Status OK and the post URN in the header but when i try getting the post data using the given URN i'm getting error 404.
Here is the function that i am using to upload the video to LinkedIn.
const uploadVideo = async (linkedinId, accessToken, videoUrl) => {
/* Fetching video from Google storage */
const videoData = await axios.get(videoUrl, { responseType: 'arraybuffer' });
const contentType = videoData.headers['content-type'];
const videoSize = videoData.headers['content-length'];
const url = 'https://api.linkedin.com/rest/videos';
const body = {
initializeUploadRequest: {
owner: `urn:li:organization:${linkedinId}`,
fileSizeBytes: Number(videoSize),
},
};
const headers = {
Authorization: `Bearer ${accessToken}`,
'X-Restli-Protocol-Version': '2.0.0',
'x-li-format': 'json',
'LinkedIn-Version': 202207,
};
const response = await axios.post(url, body, { headers, params: { action: 'initializeUpload' } });
const { uploadInstructions } = response.data.value;
const asset = response.data.value.video;
/* Uploading video */
try {
const uploadPromises = uploadInstructions.map(async ({ uploadUrl, firstByte, lastByte }) => {
const arrayBuffer = videoData.data.slice(firstByte, lastByte);
return axios({
url: uploadUrl,
method: 'POST',
data: arrayBuffer,
headers: {
'Content-Type': contentType,
},
maxBodyLength: Infinity,
maxContentLength: Infinity,
});
});
const uploadResponses = await Promise.all(uploadPromises);
const finalizeUploadBody = {
finalizeUploadRequest: {
video: asset,
uploadToken: '',
uploadedPartIds: uploadResponses.map((uploadResponse) => uploadResponse.headers.etag),
},
};
await axios.post(url, finalizeUploadBody, {
headers: {
...headers,
'Content-Type': 'application/json',
},
params: {
action: 'finalizeUpload',
},
});
} catch (error) {
throw error;
}
return asset;
};
Here is the function that i am using to publish the post to LinkedIn.
const publishContent = async (
linkedinId,
accessToken,
media,
) => {
const url = 'https://api.linkedin.com/rest/posts';
const body = {
author: `urn:li:organization:${linkedinId}`,
commentary: 'content',
visibility: 'PUBLIC',
lifecycleState: 'PUBLISHED',
distribution: {
feedDistribution: 'MAIN_FEED',
},
};
const asset = await uploadVideo(linkedinId, accessToken, media.urls[0], isPage);
body.content = {
media: {
title: 'Title',
id: asset,
},
};
const headers = {
Authorization: 'Bearer ' + accessToken,
'X-Restli-Protocol-Version': '2.0.0',
'x-li-format': 'json',
'LinkedIn-Version': 202207,
};
return axios.post(url, body, { headers });
};
Look at my code, what am I doing wrong? I need to get https://graph.microsoft.com/v1.0/users/${uniqueName}/manager. But the request fails
But when I try to execute the https://graph.microsoft.com/v1.0/${uniqueName} query, everything goes well. What to fix so that the https://graph.microsoft.com/v1.0/users/${uniqueName}/manager request is successful?
fastify.post('/login', {
preHandler: (request, _, next) => {
if (!request.body || !request.body.username || !request.body.password) {
const error = new Error('Credentials are missing');
error.statusCode = 400;
return next(error);
}
return next();
},
}, async (request, reply) => {
const { username, password } = request.body;
const userData = await fastify.helpers.authentication.getUserTokens(username, password, azureConfig.CLIENT_SCOPE);
await replyWithTokens(fastify, reply, userData);
});
And next
const getUserTokens = async (username, password, scope) => {
const authUrl = `https://login.microsoftonline.com/${azureConfig.TENANT_NAME}/oauth2/v2.0/token`;
const body = {
client_id: azureConfig.CLIENT_ID,
client_secret: azureConfig.CLIENT_SECRET,
grant_type: 'password',
password,
scope,
username,
};
const authResponse = await fetch(authUrl, {
body: new URLSearchParams(body).toString(),
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
method: 'POST',
});
if (!authResponse.ok) {
fastify.helpers.error.throwError(422, 'Authentication failed');
}
const result = await authResponse.json();
const decodedData = jwt.decode(result.access_token);
const uniqueName = String(decodedData.unique_name || '').toLowerCase();
const name = String(decodedData.upn || uniqueName).toLowerCase();
const agentAttributes = {};
if (!uniqueName) {
fastify.helpers.error.throwError(400, 'Unique name not found');
}
let recheckSan = true;
let san = name.split('#').shift();
let agent = await fastify.db.models.Agent.findOne({
where: { uniqueName },
});
let radId = '';
const graphAuthResponse = await fetch(authUrl, {
body: new URLSearchParams({
...body,
scope: 'email openid profile https://graph.microsoft.com/User.Read',
}).toString(),
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
method: 'POST',
});
if (graphAuthResponse.ok) {
const graphAuthResult = await graphAuthResponse.json();
const { access_token: graphAccessToken = '' } = graphAuthResult;
// eslint-disable-next-line max-len
const graphResponse = await fetch(`https://graph.microsoft.com/v1.0/users/${uniqueName}/manager`, {
headers: {
authorization: `Bearer ${graphAccessToken}`,
'content-type': 'application/json',
},
});
if (graphResponse.ok) {
const graphResult = await graphResponse.json();
console.log(graphResult)
}
}
}
I want to receive such response
{
"#odata.context": "https://graph.microsoft.com/v1.0/$metadata#directoryObjects/$entity",
"#odata.type": "#microsoft.graph.user",
"id": "1111112-68cf-4896-b2d0-13b5c6264113",
"businessPhones": [
"111 111 11111"
],
"displayName": "Wer, John",
"givenName": "John",
"jobTitle": "SENIOR DEVELOPMENT ARCHITECT",
"mail": "somemail#mail.com",
"mobilePhone": "111 111 1111",
"officeLocation": "Atlanta",
"preferredLanguage": null,
"surname": "John",
"userPrincipalName": "somemail#mail.com"
}
But I get such an error response. What am I doing wrong? Thanks!
{
"error": {
"code": "Authorization_RequestDenied",
"message": "Insufficient privileges to complete the operation.",
"innerError": {
"date": "2022-01-14T20:40:30",
"request-id": "9e2b5937-4bd0-4fdb-a1ae-1b22cef09772",
"client-request-id": "9e2b5937-4bd0-4fdb-a1ae-1b22cef09772"
}
}
}
To get the managers of other users in your organization on your behalf, you need to have User.Read.All delegated permission
Once the permission is assigned, admin consent needs to be granted for the same.
Then you would be able to fetch the managers info of other users in your organization
You can test the same in Graph Explorer first. If it is successful, you can make the changes accordingly in your JavaScript code
I want to delete a user from firebase. And my action is called from a button.
`
export const deleteAccount = () =>{
return async (dispatch, getState) =>{
const token =getState().auth.token;
let response;
try{
response = await fetch('https://identitytoolkit.googleapis.com/v1/accounts:delete?
key=[My_API_key]',
{
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
token:token
})
});
} catch(err){
throw new Error(err.message);
}
if(!response.ok){
const errorResData = await response.json();
console.log(errorResData);
const errorId = errorResData.error.message;
let message = 'Something went Wrong!';
if(errorId === 'INVALID_ID_TOKEN'){
message = 'Please Login Again!!'
} else if(errorId === "USER_NOT_FOUND"){
message = 'User Not Found';
}
throw new Error(message);
}
// dispatch(authentication(resData.localId, resData.idToken, parseInt(resData.expiresIn)*1000 ));
dispatch({type: DELETE});
}
};
`
on consoling my errorResData I am getting response
Object { "error": Object { "code": 400, "errors": Array [ Object { "domain": "global", "message": "MISSING_ID_TOKEN", "reason": "invalid", }, ], "message": "MISSING_ID_TOKEN", }, }
if I console my token I am getting that token.
Thanks in advance!!
I'm not entirely sure why you aren't using the Firebase SDK to do this, but you should be using v3 of the Identity Toolkit API.
await fetch(
"https://www.googleapis.com/identitytoolkit/v3/relyingparty/deleteAccount",
{
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
idToken: FRESH_USER_ID_TOKEN
})
}
);
I need to send a picture using axios, then output its url to the console. The backend works fine, it gives an array and the picture is loaded into the folder. But for some reason I cannot output to the front through then to the console. Doesn't output anything at all, although the backend returns that the picture was successfully loaded
const uploadImage = file => {
return new Promise((resolve, reject) => {
let formData = new FormData()
formData.append('imagesUp', file)
const config = {
headers: {
'Content-Type': 'multipart/form-data',
Folder: 'editor',
},
}
axios.post('/api/upload', formData, config).then(responseImage => {
console.log(responseImage)
resolve({ data: { link: '//werafgrswe' } })
})
})
}
{
"status": "success",
"message": "File uploaded successfully",
"data": [
{
"_id": 0,
"name": "2020result-global-town-1609439624185.jpg",
"path": "/uploads/editor/2020result-global-town-1609439624185.jpg",
"size": "1.13 MB"
}
]
}```
Remove additional Promise
const uploadImage = (file) => {
let formData = new FormData();
formData.append("imagesUp", file);
const config = {
headers: {
"Content-Type": "multipart/form-data",
Folder: "editor"
}
};
return axios.post("/api/upload", formData, config).then((responseImage) => {
return responseImage.data;
});
};
React.useEffect(() => {
uploadImage(file).then((data) => {
console.log(data);
});
}, [file]);
I’m trying to put a buffer in a request because I have a list of data to import. I want to have success request after one another. The problem I’m encountering is that it waits to upload all data of the request.
Here is the sample data:
[
{
"contacts": "dsds#dsd.com",
"recipient": "dsd#dsd.com",
"date_sent": "07/08/2020 17:05:04",
"subject": "repurchase"
},
{
"contacts": "asd#ret.com",
"recipient": "test#yahoo.com",
"date_sent": "07/10/2020 17:31:51",
"subject": "biz"
},
{
"contacts": "we#sdf.com",
"recipient": "abc#yahoo.com",
"date_sent": "07/09/2020 13:02:54",
"subject": "rock"
}
];
const createEngage = async(body) => {
const BASE_URL = '/api/import'
var requestOptions = {
method: 'POST',
headers: {
'Accept': 'application/json',
"Content-Type": "application/json"
},
body: body
};
fetch(BASE_URL, requestOptions)
.then(response => response.text())
.then(async result => {
console.log(result);
})
.catch(error => console.log('error', error));
}
What you probably want to do is to loop over your data and use async / await to wait at each iteration. Your implementation of your asynchronous function currently does not await anything. Instead it should await the fetch request and the decoding of the body with response.text().
Check the response for errors and wrap the fetch request in a try...catch block. If an error occurs then the catch block will be executed. Otherwise check the response object for any states or errors you want to include.
const data = [
{
"contacts": "dsds#dsd.com",
"recipient": "dsd#dsd.com",
"date_sent": "07/08/2020 17:05:04",
"subject": "repurchase"
},
{
"contacts": "asd#ret.com",
"recipient": "test#yahoo.com",
"date_sent": "07/10/2020 17:31:51",
"subject": "biz"
},
{
"contacts": "we#sdf.com",
"recipient": "abc#yahoo.com",
"date_sent": "07/09/2020 13:02:54",
"subject": "rock"
}
];
const BASE_URL = '/api/import'
/**
* Sends a request for each individual item.
*/
const createEngage = async body => {
const requestOptions = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body
};
try {
const response = await fetch(BASE_URL, requestOptions);
if (!response.ok) {
alert('Your request has failed');
return null;
}
const text = await response.text();
return text;
} catch(error) {
alert('Your request caused an error');
}
};
/**
* Loop over each item and call createEngage.
* Wait for the request to finish and continue.
*/
const createMultipleEngages = async data => {
for (const item of data) {
const result = await createEngage(item); // This will make the loop wait every time.
console.log(result);
}
};
// Call the function and start looping.
createMultipleEngages(data);