If I use the library #microsoft/microsoft-graph-client, I can get the contact photo as binary data, convert it to base64 and get the correct photo with the code below:
const request = require('request')
const microsoftGraph = require('#microsoft/microsoft-graph-client');
let token = token-value
let client = getMicrosoftGrapClient(token);
let id = contact-id;
let url = '/me/contacts/' + id + '/photo/$value';
client.api(url).get().then((res) => {
//console.log(res);
var encodedImage = new Buffer(res, 'binary').toString('base64');
console.log("encodedImage>>>>>>>>>>>>>>>>>>>>>>")
console.log (encodedImage);
}).catch((err) => {
console.log(err);
});;
function getMicrosoftGrapClient (token) {
// Create a Graph client
return microsoftGraph.Client.init({
authProvider: (done) => {
// Just return the token
done(null, token);
}});
}
I cannot get the correct contact photo with the HTTP GET. The HTTP
response code is 200 but the body is not the binary data of photo.
Please let me know what the error is. Here is the code:
const request = require('request')
request({
url: "https://graph.microsoft.com/v1.0/me/contacts/{contact_id}/photo/$value",
method: 'GET',
headers: {
'content-type': 'image/jpg',
'Authorization': 'Bearer {token}'
}
}, function (error, response, body){
console.log(error);
var encodedImage = new Buffer(body, 'binary').toString('base64');
console.log(encodedImage);
});
Encoding needs to be explicitly specified as
encoding: null
In that case the body will be of type Buffer, instead of the default (string).
And content-type could be omitted.
Example
request({
url: "https://graph.microsoft.com/v1.0/me/photo/$value",
method: 'GET',
encoding: null,
headers: {
'Authorization': 'Bearer ' + accessToken,
}
}, function (error, response, body) {
var encImage = new Buffer(body, 'binary');
fs.writeFileSync(filePath, encImage );
});
Related
first way I tried is :
static async callSendApi(requestBody) {
let url = new URL(
`${API_URL}/${PAGE_ID}/messages`
);
url.search = new URLSearchParams({
access_token: `${PAGE_ACCESS_TOKEN}`,
});
console.warn("Request body is\n" + JSON.stringify(requestBody));
let response = await axios.post(url, {
headers: { "Content-Type": "application/json" },
body: JSON.stringify(requestBody),
// access_token: `${PAGE_ACCESS_TOKEN}`,
});
if (!response.ok) {
consoleconst`Unable to call Send API: ${response.statusText}`,
await response.json();
}
}
Second way I tried is :
static async callSendApi(requestBody) {
let url = new URL(
`${API_URL}/${PAGE_ID}/messages?access_token=${PAGE_ACCESS_TOKEN}`
);
/* url.search = new URLSearchParams({
access_token: `${PAGE_ACCESS_TOKEN}`,
});*/
console.warn("Request body is\n" + JSON.stringify(requestBody));
let response = await axios.post(url, {
headers: { "Content-Type": "application/json" },
body: JSON.stringify(requestBody),
// access_token: `${PAGE_ACCESS_TOKEN}`,
});
if (!response.ok) {
consoleconst`Unable to call Send API: ${response.statusText}`,
await response.json();
}
}
the error I get :
error: {
message: 'Unknown path components: /messagesaccess_token=access_token
type: 'OAuthException',
code: 2500,
fbtrace_id: 'AbBJGVotjz3ijKKLzVE6_CM'
}
I'm receiving this error in both ways. both ways are escaping the '?' mark. I have no idea what is happening.. I'm using heroku for this. I tried deleting and redeploying the repository to confirm if the code is not updating. but still gives this error. :( .
I tried withot using URL and URLSearchParams and it worked!
below is my code:
static async callSendApi(requestBody) {
console.warn("Request body is\n" + JSON.stringify(requestBody));
let response = await axios.post(
`${API_URL}/${PAGE_ID}/messages`,
{
params: { access_token: `${PAGE_ACCESS_TOKEN}` },
},
{
headers: { "Content-Type": "application/json" },
body: JSON.stringify(requestBody),
}
);
if (!response.ok) {
consoleconst`Unable to call Send API: ${response.statusText}`,
await response.json();
}
}
I am trying to integrate a POST API call from a lambda function using Node.js 12.x.
I tried like below:
var posturl = "My post api path";
var jsonData = "{'password':'abcdef','domain':'www.mydomain.com','username':'abc.def'}";
var req = require('request');
const params = {
url: posturl,
headers: { 'jsonData': jsonData }
};
req.post(params, function(err, res, body) {
if(err){
console.log('------error------', err);
} else{
console.log('------success--------', body);
}
});
But when I am execute it using state machine, I am getting the below exception:
{
"errorType": "Error",
"errorMessage": "Cannot find module 'request'\nRequire stack:\n- /var/task/index.js\n- /var/runtime/UserFunction.js\n- /var/runtime/index.js",
"trace": [
"Error: Cannot find module 'request'",
"Require stack:",
"- /var/task/index.js",
"- /var/runtime/UserFunction.js",
"- /var/runtime/index.js",
" at Function.Module._resolveFilename (internal/modules/cjs/loader.js:815:15)",
" at Function.Module._load (internal/modules/cjs/loader.js:667:27)",
" at Module.require (internal/modules/cjs/loader.js:887:19)",
" at require (internal/modules/cjs/helpers.js:74:18)",
" at Runtime.exports.handler (/var/task/index.js:8:14)",
" at Runtime.handleOnce (/var/runtime/Runtime.js:66:25)"
]
}
Here the posturl is my api path and jsondata is my key value pair data.
So How can I call a POST API from lambda function? How can I pass the entire jsondata key when call API? How can I parse the response after the service call?
Update: I have tried like below
All my details are passing with a key jsonData, where I can specify that? Without that key, it will not work.
exports.handler = (event, context, callback) => {
const http = require('http');
const data = JSON.stringify({
password: 'mypassword',
domain: 'www.mydomain.com',
username: 'myusername'
});
const options = {
hostname: 'http://abc.mydomain.com',
path: 'remaining path with ticket',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': data.length
}
};
const req = http.request(options, (res) => {
let data = '';
console.log('Status Code:', res.statusCode);
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
console.log('Body: ', JSON.parse(data));
});
}).on("error", (err) => {
console.log("Error: ", err.message);
});
req.write(data);
req.end();
};
source : How to Make an HTTP Post Request using Node.js
const https = require('https');
const data = JSON.stringify({
name: 'John Doe',
job: 'Content Writer'
});
const options = {
hostname: 'reqres.in',
path: '/api/users',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': data.length
}
};
const req = https.request(options, (res) => {
let data = '';
console.log('Status Code:', res.statusCode);
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
console.log('Body: ', JSON.parse(data));
});
}).on("error", (err) => {
console.log("Error: ", err.message);
});
req.write(data);
req.end();
I am using formData to POST an image I uploaded via ImagePicker. I am sending the parameters like so:
let formData = new FormData();
formData.append('image', { uri: localUri, name: filename, type });
formData.append('description', 'this is the decription');
return await fetch('https://prana-app.herokuapp.com/v1/visions/', {
method: 'POST',
body: formData,
header: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-User-Email': this.state.email,
'X-User-Token': this.state.accessToken
},
});
};
This doesn't seem to work, as I am getting a very generic NoMethodError (undefined methodbuild' for nil:NilClass):` error.
How can I POST my parameters in the correct way given that the image parameter is an image and the description parameter is a string?
Thanks
Content-Type must be different when using Formdata.
example.js:
fileSend = () => {
const apiUrl = "http://00.000.00.000:0000/upload";
const uri = this.state.image;
const stringdata = {
username: this.state.name,
introduce: this.state.introducetext,
addresstext: this.state.addresstext
};
const uriParts = uri.split(".");
const fileType = uriParts[uriParts.length - 1];
const formData = new FormData();
formData.append("userfile", {
uri,
name: `photo.${fileType}`,
type: `image/${fileType}`
});
for (var k in stringdata) {
formData.append(k, stringdata[k]);
}
const options = {
method: "POST",
body: formData,
headers: {
Accept: "application/json",
"Content-Type": "multipart/form-data"
}
};
return fetch(apiUrl, options)
As shown in the example above, Content-Type should write multipart/form-data and pass it over to For ... in if Stringdata is not one.
I am calling a Twilio Studio Flow Rest API from a Twilio function.
Following is the function code:
exports.handler = function(context, event, callback) {
const request = require('request');
to = event.to;
to = to.replace(/[()-.]/g, '');
to = to.replace(/ /g, '');
var postoptions = {
headers: {'AC' : 'b1xx'},
url: 'https://studio.twilio.com/v1/Flows/FWxxx8/Executions',
method: 'POST',
data: { 'from': '+1814xxx',
'to': to
}
};
request(postoptions, function(error, response, body){
callback(null, response);
});
};
The function keeps saying the Account SID adn auth token are incorrect. However sid and token are correct.
What I am missing?
You'll need to "base64" encode the Account SID and auth token when you pass them in headers.
Try something like this:
exports.handler = function (context, event, callback) {
const request = require('request');
to = event.to;
to = to.replace(/[()-.]/g, '');
to = to.replace(/ /g, '');
var username = "AC";
var password = "b1xx";
var auth = "Basic " + new Buffer(username + ":" + password).toString("base64");
var postoptions = {
headers: { 'Authorization': auth },
url: 'https://studio.twilio.com/v1/Flows/FWxxx8/Executions',
method: 'POST',
data: {
'from': '+1814xxx',
'to': to
}
};
request(postoptions, function (error, response, body) {
callback(null, response);
});
};
I am using Angular2 in my application, And I saw advantages of using Observable while calling http calls. But somehow I am not able to make call when I am using Observable for POST requests, But it's working while GET request. If I use subscribe method, then POST is working.
Below is my code,
using Observable,
AddBreakoutsManually(breakoutUploads: Uploads): Observable<boolean> {
console.log("Data = ", JSON.stringify(breakoutUploads));
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this.http.post("/breakout/InsertUploads", JSON.stringify(breakoutUploads), options)
.map((res: Response) => res.json())
.catch((error: any) => Observable.throw(error.json().error || 'Server error'));
}
Using subscribe,
Adding(breakoutUploads: Uploads) {
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
this.http
.post('/breakout/InsertUploads', JSON.stringify(breakoutUploads), options)
.subscribe(data => {
alert('ok');
}, error => {
console.log(error.json());
});
}
My API,
[HttpPost]
public bool InsertUploads([FromBody]BreakoutUpload breakoutUploads)
{
return true;
}
What mistake I am making while using observable in POST call ?
Not sure what I changed, But it starts working with below code,
AddBreakoutsManually(breakoutUploads: Uploads): Observable<string> {
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this.http.post(Configuration.Url_AddBreakoutsManually, JSON.stringify(breakoutUploads), options) // ...using post request
.map((res: Response) => res.json())
.catch((error: any) => Observable.throw(error.json().error || 'Server error'));
}