Sending binary body in node.js HTTPS post - node.js

I have the following code that takes base64 string, and send it to API that accepts binary. I am getting empty response from the api call
let base64String = event.base64String;
// pass the base64 string into buffer
let buffer = new Buffer(base64String, 'base64');
// TODO check file type
processImage(buffer)
.then(result => {
console.log("result are " + result);
callback(result);
}).catch(error => callback(error));
let processImage = function (buffer) {
// get the file extension
return new Promise((resolve, reject) => {
var options = {
method: 'POST',
url: 'https://<UR - not visible for privacy>',
headers:
{
'Content-Type': 'application/octet-stream'
},
body: buffer.toString('binary')
};
request(options, function (error, response, body) {
if (error) reject(error);
console.log(body);
resolve(body);
});
}
Equivalent in postman is that I simply specify binary in body and attach file, again post call but URL is removed from pic, the header is content-type: application/octet-stream, it works in postman but not in node.js

Related

HTTPS POST in shift-jis encoding

I'm trying to send a POST request to a server which decodes with SHIFT-JIS.
This string サービス is being translated to 繧オ繝シ繝薙せ after being decoded in SHIFT-JIS.
It seems like the request will always be encoded in UTF-8 whenever the request is being sent over.
I'm using nodejs for posting the request.
Question is how do I send over the characters in shift-jis encoding? It seemed easy but I just couldn't find out how to.
Listening server
var iconv = require('iconv-lite');
const http = require('http');
http.createServer((request, response) =>
{
const
{
headers,
method,
url
} = request;
let body = [];
request.on('error', (err) =>
{
console.error(err);
}
).on('data', (chunk) =>
{
body.push(chunk);
}
).on('end', () =>
{
body = Buffer.concat(body).toString();
// BEGINNING OF NEW STUFF
body = iconv.decode(Buffer.from(body), 'shift_jis');
response.on('error', (err) =>
{
console.error(err);
}
);
response.statusCode = 200;
response.setHeader('Content-Type', 'application/json');
// Note: the 2 lines above could be replaced with this next one:
// response.writeHead(200, {'Content-Type': 'application/json'})
const responseBody =
{
headers,
method,
url,
body
};
response.write(JSON.stringify(responseBody));
console.log(body);
console.log(responseBody);
response.end();
// Note: the 2 lines above could be replaced with this next one:
// response.end(JSON.stringify(responseBody))
// END OF NEW STUFF
}
);
}
).listen(8000);
Request
var request = require('request');
request({
url: 'http://localhost:8000',
headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=shift_jis' },
method: 'POST',
body: 'サービス'
}, function(error, response, body){
if(error) {
console.log(error);
} else {
console.log(response.statusCode, body);
}
});
EDIT: It turns out that the axios module we're using for HTTPS POST will encode the payload in UTF-8 before sending out the request. We cloned the axios module and modifying it to encode in SHIFT-JIS instead.
If you want to send a string with Shift-JIS encoding, you have to convert the target string (it is represented in UTF-16 internally) into Shift-JIS before adding it into the request body.
The standard TextEncoder only supports UTF-8 encoding and cannot handle Shift-JIS encoding. So you have to use additional modules like encoding.js or text-encoding for this purpose.

I can't save the response of a request request in node.js

I created a login function that receives the mail and the pass, to receive the jwt. I have tried that the function returns the jwt but I have not succeeded.
This is the method that I have developed, it has a post request that sends the mail and pass parameters. in the resp variable I try to save the request response, but when invoking the function it prints :
undefined.
login(mail, pass) {
var options = {
'method': 'POST',
'url': 'https://inventario.demos.adlnetworks.com/api/login',
'headers': {
'Content-Type': 'application/json'
},
body: JSON.stringify({ "email": mail, "password": pass })
};
var resp;
var req = request(options, function(error, response) {
if (error) throw new Error(error);
resp = response.body;
});
return resp;
}
The problem is that "request" is an async function. You can't do this
var resp;
var req = request(options, function(error, response) {
if (error) throw new Error(error);
resp = response.body;
});
return resp;
Because "resp" always be undefined. You would need to do something like this
var resp;
var req = request(options, function(error, response) {
if (error) throw new Error(error);
return response.body;
});
But it wont work for you.
The short and easy solution is change the library to make http request, and use "async" and "await" to use easily async functions.
For example:
const fetch = require('node-fetch');
async function main(){
const data = await login();
console.log(data);
}
async function login(){
const url = "https://jsonplaceholder.typicode.com/posts";
const data = {
title: 'foo22222',
body: 'ba222r',
userId: 1
};
const response = await fetch(url, {
method: 'POST',
body: JSON.stringify(data),
headers: {
"Content-type": "application/json; charset=UTF-8"
}
});
const json = await response.json()
return json;
}
main();
In this case i use "node-fetch" library and consume a backend (in login function) that create a post and return its response.

upload an image file to sharepoint via api graph

I am trying to upload an image file from my node.js application to a group's drive in Sharepoint.
As the official documentation states, I'm making my request as follows:
PUT /groups/{group-id}/drive/items/{parent-id}:/{filename}:/content
With the binary image in the body: "The contents of the request body should be the binary stream of the file to be uploaded."
The problem is that the image is uploaded but as a corrupted file. I tried different solutions and still don't see why is always the image corrupted.
Here is my code:
//i get my image from a URL first
https.get(url.parse(attachment.contentUrl), function (response) {
var data = [];
response.on('data', function (chunk) {
data.push(chunk);
});
response.on('end', function () {
if (response.statusCode === 200) {
var buffer = Buffer.concat(data);
//store my image in a local file to test if image is correct (which it is)
fs.writeFile(localFileName, buffer, (fsError) => {
//error handling
});
functions.uploadImageToSharepoint(session, localFileName, buffer,
function (err, body, res) {
if (err) {
console.error(err);
}else{
console.log('OK!');
}
});
} else {
//error handling
}
});
}).on('error', function (e) {
console.log("error2: " + e);
});
//and the request to graph api
function uploadImageToSharepoint(session, fileName, data, callback) {
var options = {
url: 'https://graph.microsoft.com/v1.0/groups/xxxxxxx/drive/root:/yyyyyy/fileName.jpg:/content',
method: 'PUT',
body: data,
json: true,
headers: {
'Content-Type': 'image/jpg',
Authorization: 'Bearer ' + session.userData.accessToken
}
};
request(options, function (err, res, body) {
if (err) return callback(err, body, res);
if (parseInt(res.statusCode / 100, 10) !== 2) {
if (body.error) {
return callback(new Error(res.statusCode + ': ' + (body.error.message || body.error)), body, res);
}
return callback(err, body, res);
}
callback(err, body ,res);
});
}
The file is most likely getting corrupted due to the following option for request:
var options = {
json: true, //<--setting this option sets body to JSON representation of value
//another properties are omitted for clarity
};
In that case request sets body to JSON representation of value and adds accept header to application/json for Upload endpoint and binary file get corrupted.
The solution would be to omit json option from a request and use the proper content-type only:
var options = {
url: '/me/drive/root:/filename.jpg:/content',
method: 'PUT',
body: data,
headers: {
'Content-Type': 'image/jpg',
Authorization: 'Bearer ' + accessToken
}
};

Unable to access response object data outside the function in node js

I am using node js and making a call to spotify API and receive the response in body object, as shown in below code:
var options = {
url: 'https://api.spotify.com/v1/me',
headers: { 'Authorization': 'Bearer ' + access_token },
json: true
};
request.get(options, function(error, res, body) {
console.log(body)
});
This gives me output:
But now when I try to access the body object outside the function I get undefined. I think the problem is that I am making an asynchronous call and so before the response is received the statements where I make use of body variable outside function are executed. But I am a bit confused about how to get to the solution.
Any help is appreciated
Edit:
request.get(options, function(error, res, body) {
console.log(body)
response.render('user_account.html', {
data: body
})
});
And it gives the output:
Use promise.
You can try following:
const apiCall = () => {
return new Promise((resolve, reject) => {
var options = {
url: 'https://api.spotify.com/v1/me',
headers: { 'Authorization': 'Bearer ' + access_token },
json: true
};
request.get(options, function(error, res, body) {
if(error) reject(error);
console.log(body);
resolve(body);
});
});
}
apiCall().then((body) => {
// do your things here
})
.catch((err) => console.log(err));

NodeJS String to Buffer pdf file

Hi guys i'm trying to download a pdf file and save it on my disk. The API send me a string. But the following code not working.
axios.get('https://myapi.com/download', config).then((res) => {
var buff = Buffer.from(res.data, 'binary');
fs.writeFile('file.pdf', buff, function (err) {
if (err) throw err;
console.log('Saved!');
});
}).catch((e) => {
console.log(e);
})
I've tried it, and working ...
fs.readFile('./download.pdf','binary', function (err, data) {
var str = data.toString();
var buff = Buffer.from(str, 'binary');
fs.writeFile('novopdf.pdf',buff, () => {
console.log('ok');
})
});
You need to config axios get request as follows
const response = await Axios({
method: 'GET',
url: url,
responseType: 'stream'
})
response.data.pipe(Fs.createWriteStream(path)) // path is location where you want to write the file.
Then check for end event on the response object.

Resources