I'm trying to parse the logged in user's photo on node.js using graph API and something is not correct about the generated base64, I've tried different combinations and the photo is always corrupt.
export async function getPhotofromMsGraph(
accessToken: string,
): Promise<string | undefined> {
const config = {
headers: {
Authorization: `Bearer ${accessToken}`,
ResponseType: 'arraybuffer',
},
};
return axios
.get(graphConfig.graphPhotoEndpoint, config)
.then((response) => {
const { data } = response;
if (data) {
var imageType = 'image/jpeg';
var imageBytes = Buffer.from(data).toString('base64');
var imageSrc = `data:${imageType};base64,${imageBytes}`;
return imageSrc;
}
return undefined;
})
.catch((error) => {
throw error;
});
}
Related
I am attempting to use a form in Remix to add a file and then upload that file to WhatsApp using their Cloud API Media Upload endpoint. Below is my initial code within the action. The current error I am receiving is message: '(#100) The parameter messaging_product is required.. I feel like this error may be misleading based off the form data I have appended with the "messaging_product".
export async function action({ request, params }: ActionArgs) {
const uploadHandler = unstable_composeUploadHandlers(
async ({ name, contentType, data, filename }) => {
const whatsAppPhoneId = process.env.WHATSAPP_PHONE_ID;
const whatsAppToken = process.env.WHATSAPP_ACCESS_TOKEN;
const dataArray1 = [];
for await (const x of data) {
dataArray1.push(x);
}
const file1 = new File(dataArray1, filename, { type: contentType });
const graphApiUrl = `https://graph.facebook.com/v15.0/${whatsAppPhoneId}/media`;
const formData = new FormData();
formData.append("file", file1);
formData.append("messaging_product", "whatsapp");
formData.append("type", contentType);
try {
const imageMediaResponse = await fetch(graphApiUrl, {
method: "POST",
headers: {
Authorization: `Bearer ${whatsAppToken}`,
"Content-Type": "multipart/form-data",
},
body: formData,
});
const imageMedia = await imageMediaResponse.json();
return imageMedia?.id;
} catch (error) {
console.error(error);
}
const whatsAppMediaId = await uploadWhatsAppImageMedia(
whatsAppPhoneId,
whatsAppToken,
data,
filename,
contentType
);
}
);
const formData = await unstable_parseMultipartFormData(
request,
uploadHandler
);
}
I use nuxt3/node.js with multer ,
i can't store or receive file in my server and i can't see req.file in root, its empty all time.
server Code:
const upload = multer({ dest: './uploads/' })
router.post('/sendNewQuestionCSV', upload.single('csv'),adminControler.sendNewQuestionCSV.bind(adminControler))
and my FrontEnd Code with nuxt3:
async function fileSelected(e) {
let formData = new FormData();
formData.append("csv", e.target.files[0]);
const res = await $postFetch("/admin/sendNewQuestionCSV", formData, {
"Content-Type": "multipart/form-data",
});
}
note:$postFetch is an method i made my self use fetch and third argument is "headers". its a nuxt3 Plugin
this Plugin code:
export default defineNuxtPlugin(async () => {
return {
provide: {
postFetch: async (url, body,headers={}) => {
let token = useCookie('token');
return await $fetch(url, {
method: 'post',
body: { token: token.value, ...body },
baseURL: useRuntimeConfig().API_BASE,
...headers
}).catch((error) => error.data)
}
}
}
})
try using .append to add the token:
postFetch: async (url, body,headers={}) => {
let token = useCookie('token');
body.append('token', token.value);
return await $fetch(url, {
method: 'post',
body: body,
baseURL: useRuntimeConfig().API_BASE
}).catch((error) => error.data)
}
EDIT
also try removing headers
Hi I made a module and when I try to return the song name it is just undefined, the console.log just before it works though so I'm a little confused. The line after console.log(`"${songName}" by ${artistsList}`) is where the issue is, I try to return "${songName}" by ${artistsList} but the return is just undefined so I am a little stuck on why
Code: (This is the spotify.js module)
I call it with const Spotify = require("./spotify.js"), everything works up until I need to just return the song name using the Spotify.request() function
const axios = require("axios");
module.exports = {
token: "",
ref: "",
refresh: function () {
axios({
method: "post", //you can set what request you want to be
url: "https://accounts.spotify.com/api/token",
data:
`grant_type=refresh_token&refresh_token=${this.ref}`,
headers: {
Authorization:
"Basic ",
"Content-Type": "application/x-www-form-urlencoded"
}
}).then(response => {
this.token = response.data.access_token
console.log(`Successfully refreshed token ${module.exports.token}`);
});
},
analyseSong: function (data) {
console.log(data)
const x = data;
//console.log(x)
if (x.is_playing) {
const songNameMatch = x.item.name.split("(");
var songName = x.item.name;
try {
const letter = songNameMatch[1].charAt(0);
letter.toLowerCase() == "f" ||
songNameMatch[1].toLowerCase().match(/^with/)
? (songName = songNameMatch[0].trim())
: false;
} catch (err) {
false;
}
var artistArray = [];
var artist;
const artists = x.item.artists;
//console.log(token)
for (artist in artists) {
artistArray.push(x.item.artists[artist].name);
}
//console.log(artistArray)
const artistsList = artistArray.join(", ");
//console.log(artistsList)
//console.log(`Currently playing: ${songName} - ${artistsList}`);
console.log(`"${songName}" by ${artistsList}`)
return `"${songName}" by ${artistsList}`;
} else {
return `Not currently listening to a song`;
}
},
request: function () {
axios
.get("https://api.spotify.com/v1/me/player/currently-playing", {
headers: { Authorization: `Bearer ${this.token}` }
})
.then(function (response) {
module.exports.analyseSong(response.data);
})
},
}
So I'm doing X=Spotify.request() trying to get the song name as X so I can output using IRC chat
There are a couple problems. .request() has no return value at all. So, it will never return anything other than undefined. You can fix that like this by adding two return statements, the first to return the promise itself and the second to make the return value from analyseSong() be the resolved value of that promise:
request: function () {
return axios
.get("https://api.spotify.com/v1/me/player/currently-playing", {
headers: { Authorization: `Bearer ${this.token}` }
})
.then(function (response) {
return module.exports.analyseSong(response.data);
})
},
Now Spotify.request() will return a promise that will resolve with the value returned from .analyseSong(response.data). You would use that promise like this:
Spotify.request().then(result => {
console.log(result);
}).catch(err => {
console.log(err);
});
After successfully integrating a 3rd party REST Oauth Api, now i am trying to convert the api logic into a graphql query but i'm kind of stuck on how best to architect the query.
From a REST perspective, i have something like this that works 100%
app.get("/auth/redirect", async (req: Request, res:Response) => {
const code = req.query.code
const { access_token, account_id } = await getTokens({
code,
clientId,
clientSecret,
})
try{
const result = await axios
.get(
`https://api.specificservice.dev/helloworld/id/v1/accounts?accountId=${account_id}`,
{
headers: {
"Content-Type": "application/x-www-form-urlencoded",
Authorization: `Bearer ${access_token}`,
},
}
)
console.log('Fetching user..', result.data)
return result.data
}
catch (error: any) {
let message = error.result.data
console.log(message)
return message
}
})
from Graphql, I've got a sketch like this.
getPlatform: async (_: any, _args: any, { req }: any) => {
const clientId = "test"
const clientSecret = "test"
const code = req.query.code
const { access_token, account_id } = await getTokens({
code,
clientId,
clientSecret,
})
try{
const result = await axios
.get(
`https://api.specificservice.dev/helloworld/id/v1/accounts?accountId=${account_id}`,
{
headers: {
"Content-Type": "application/x-www-form-urlencoded",
Authorization: `Bearer ${access_token}`,
},
}
)
console.log('Fetching user..', result.data)
return result.data
}
catch (error: any) {
let message = error.result.data
console.log(message)
return message
}
},
How can I refactor this to suit what I'm trying to do from the rest endpoint
Redux Code
export const uploadImage = data => async dispatch => {
const config = {
headers: {
"Content-Type": "multipart/form-data"
}
};
try {
const res = await axios.post("/api/profile/upload", data, config);
// const res = await axios.post("/api/profile/upload", data, {
// headers: {
// "Content-Type": "multipart/form-data"
// }
// });
console.log(res);
dispatch({
type: AVATAR_UPLOAD,
payload: res.data
});
} catch (err) {
const errors = err.response.data.errors;
if (errors) {
errors.forEach(error => dispatch(setAlert(error.msg, "danger")));
}
dispatch({
type: PROFILE_ERROR,
payload: { msg: err.response.statusText, status: err.response.status }
});
}
};
React Code
const data = new FormData();
data.append("file", avatar);
uploadImage(data);
I get bad request message, req.files is empty
I try to upload file with Postman same configuration,it seems api works but can't upload with react formdata.
Any idea would be appreciated. Thanks in advance
try doing this:
const formData = new FormData();
formData.append('file', file);
const res = await axios.post("/api/profile/upload", formData, config);