How to upload multipart/form-data with axios? - node.js

I try to upload to file hosting, i debug it in firebug. i match all thing with disable javascript condition. it return empty data. in debug, it should return page that contain the file link.
const axios = require('axios').default;
const fs = require('fs');
const FormData = require('form-data');
let formData = new FormData();
formData.append('file_0', fs.readFileSync('filepath');
const fileSize = fs.statSync('filepath').size;
const userAgent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36';
axios({
method: 'post',
url: 'https://www55.zippyshare.com/upload',
headers: {
'user-agent': userAgent,
'content-length': fileSize,
'host': 'www55.zippyshare.com',
'origin': 'https://www.zippyshare.com',
'referer': 'https://www.zippyshare.com/',
'connection': 'keep-alive',
'content-type': 'multipart/form-data',
'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8'
},
data: formData
}).then(res => {
console.log(res.data)
})

Related

why Dlive bot sendMessage function always gets 'Require login' error?

I use Replit Nodejs
thats about dlive bot, The resource I found about the dlive api was very insufficient for me, so I am having a hard time.
async function sendMessage(message){
let url = 'https://graphigo.prd.dlive.tv'
let headers = {
'accept': '*/*',
'authorization': authKey,
'content-type': 'application/json',
'fingerprint': '',
'gacid': 'undefined',
'Origin': 'https://dlive.tv',
'Referer': 'https://dlive.tv/'+displayname,
'User-Agent':
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36'
}
let data = {
'operationName': 'SendStreamChatMessage',
'variables': { "input":
{
'streamer': blockchainUsername,
'message': message,
'roomRole': 'Moderator',
'subscribing': true
}
},
'extensions':{
"persistedQuery":{
"version":1,
"sha256Hash":Hash
}
},
}
response = await axios.post(url, data=JSON.stringify(data), headers=headers)
console.log(response.data)
}
sendMessage("test!")
Console:
{ errors: [ { message: 'Require login', path: [Array] } ], data: null }

Gibrish when fetching an image and sending to client

In my server i read an image - jpg - from a url with :
let _uri = "https.....xxxxxxxxxxx.jpg";
let _headers = {
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
'Accept-Encoding': '*',
'Accept-Language': 'en-US,en',
'Cache-Control': 'max-age=0',
'Connection': 'keep-alive',
'Referer': 'http://www.google.com/',
'Upgrade-Insecure-Requests': '1',
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'
}
var options = {
uri: _uri,
headers: _headers
};
rp(options)
.then(parsedBody => {
//response.setHeader('Content-Type', 'image/jpg');
// return response.status(200).send(parsedBody); //** don't work also
return response.json(parsedBody);
})
.catch(err => {
response.status(400).send(err)
});
});
No matter what i try, this will get a huge chunk of garbage when i check the response.
I can't find out what type of data is it.
On client i receive it - again - a lot of jibrish :
fetch('https://...my server')
.then(res => res.blob())
.then(blob => {
console.log(blob);
How do i get this photo on server and send to client ?
Add an option encoding: null to have the response returned as Buffer
var options = {
uri: _uri,
headers: _headers,
encoding: null // add this line
}
Then you can just send the buffer as response
rp(options)
.then(buffer => {
response.setHeader('Content-Type', 'image/jpg');
return response.status(200).send(buffer);
})

Request retuning possible gzip

I have this code:
var options = { method: 'POST',
url: '...',
headers:
{
'accept-language': 'pt-BR,pt;q=0.9,en-US;q=0.8,en;q=0.7',
'accept-encoding': 'gzip, deflate, br',
referer: '...',
'content-type': 'application/json;charset=UTF-8',
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36',
'x-csrf-jwt': `${test}`,
'x-requested-with': 'XMLHttpRequest',
origin: '...' },
body: `...` };
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});
But, the body is returning incomprehensibly. Look:
E�IU�w��Msk�������%&�vj�Xĉ�݌��0�J���Nxֈ��N�����J��{�g�������d�|��l�m�5��5�V�qs0��e�ٮ>VZE�`�`X�DX��Ed?9I�#��SO�C���u�D�<Dmn�O14WEr#�#�6���jY�9FN�p���H�Ox�7n�bt��.Vq�f�_#5��
���jJU����K���8S��)3ns��:X�]G"~� Ϯ3�Q��r�g�I��9�Ar�#�q�Γ~XcoNj�}x/#u�R��g/����L���Vs(N��o\���N��:�F�u}��zf�'�dz�'њKB���h��ۻDg��\%5�i�O��)#q�T<9��qT�~v�B�׾4Ň��|�^�k��M�� �� #IYE
This only happens with node.js
Was it returning compressed in gzip?
If so, how can I decompress it?
Add gzip: true to options and remove accept-encoding from options.headers

Logging into a website once and reusing the session using Request

I'm using request.
I want to login a website only once, then use the same connection until it expires, so I won't have to login every time I send a request.
How can I do that?
I have tried the code below, but it doesn't retain the session. I'm using Redis to save cookie values, this is probably the wrong way, though. Two cookies are generated after you log in.
var request = require("request").defaults({jar: true, followAllRedirects: true});
var options1 = {
method: 'GET',
url: 'homepageURL',
headers:
{
'cache-control': 'no-cache',
'accept-language': 'tr,en-US;q=0.9,en;q=0.8,ru;q=0.7,it;q=0.6,fr;q=0.5,de;q=0.4,es;q=0.3,sv;q=0.2,nl;q=0.1,pl;q=0.1,pt;q=0.1,nb;q=0.1',
'accept-encoding': 'gzip, deflate, br',
referer: 'URL',
accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36',
'upgrade-insecure-requests': '1'
}
};
request(options1, function (homeError, homeResponse, homeBody) {
if (homeResponse.statusCode == 200) {
var form = {"username": "myusername", "password": "mypassword", "secret": "mysecret", "action": "login"};
var options2 = {
method: 'POST',
url: 'siteurl + "/" + login.asp',
headers:
{
'cache-control': 'no-cache',
'accept-language': 'tr,en-US;q=0.9,en;q=0.8,ru;q=0.7,it;q=0.6,fr;q=0.5,de;q=0.4,es;q=0.3,sv;q=0.2,nl;q=0.1,pl;q=0.1,pt;q=0.1,nb;q=0.1',
'accept-encoding': 'gzip, deflate, br',
referer: 'URL',
accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36',
'content-type': 'application/x-www-form-urlencoded',
'upgrade-insecure-requests': '1',
origin: url + "/" + login.asp
},
form: form
};
request(options2, function (loginError, loginResponse, loginBody) {
if (loginResponse.statusCode == 200) {
console.log("Successfully logged in.");
client.set("cookie1", homeResponse.request.headers.cookie, function () {
client.set("cookie2", loginResponse.request.headers.cookie, function () {
nrp.emit('profile', {});
});
});
}
});
}
});
Profile test
nrp.on('profile', function () {
client.get("cookie1", function (cookie1Err, cookie1) {
client.get("cookie2", function (cookie2Err, cookie2) {
var cookie = cookie1 + ";" + cookie2;
var options = {
method: 'GET',
url: 'site/profile',
headers:
{
'cookie': cookie,
'accept-language': 'tr,en-US;q=0.9,en;q=0.8,ru;q=0.7,it;q=0.6,fr;q=0.5,de;q=0.4,es;q=0.3,sv;q=0.2,nl;q=0.1,pl;q=0.1,pt;q=0.1,nb;q=0.1',
'accept-encoding': 'gzip, deflate, br',
'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36',
'upgrade-insecure-requests': '1'
}
};
request(options, function (error, response, body) {
console.log(body);
// it says you are not logged in, but if you use this inside the block above, it works.
});
})
});
});

Node.js: How to send headers with form data using request module?

I have code like the following:
var req = require('request');
req.post('someUrl',
{ form: { username: 'user', password: '', opaque: 'someValue', logintype: '1'}, },
function (e, r, body) {
console.log(body);
});
How can I set headers for this?
I need user-agent, content-type and probably something else to be in the headers:
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.110 Safari/537.36',
'Content-Type' : 'application/x-www-form-urlencoded'
};
I've tried in multiple ways but I can either send header or form-data, failed to send both.
I've finally managed to do it.
Answer in code snippet below:
var querystring = require('querystring');
var request = require('request');
var form = {
username: 'usr',
password: 'pwd',
opaque: 'opaque',
logintype: '1'
};
var formData = querystring.stringify(form);
var contentLength = formData.length;
request({
headers: {
'Content-Length': contentLength,
'Content-Type': 'application/x-www-form-urlencoded'
},
uri: 'http://myUrl',
body: formData,
method: 'POST'
}, function (err, res, body) {
//it works!
});
This should work.
var url = 'http://<your_url_here>';
var headers = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:24.0) Gecko/20100101 Firefox/24.0',
'Content-Type' : 'application/x-www-form-urlencoded'
};
var form = { username: 'user', password: '', opaque: 'someValue', logintype: '1'};
request.post({ url: url, form: form, headers: headers }, function (e, r, body) {
// your callback body
});
I think it's just because you have forgot HTTP METHOD. The default HTTP method of request is GET.
You should add method: 'POST' and your code will work if your backend receive the post method.
var req = require('request');
req.post({
url: 'someUrl',
form: { username: 'user', password: '', opaque: 'someValue', logintype: '1'},
headers: {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.110 Safari/537.36',
'Content-Type' : 'application/x-www-form-urlencoded'
},
method: 'POST'
},
function (e, r, body) {
console.log(body);
});
I found the solution to this problem and It should work. I'm sure about this because I also faced the same problem
here is my solution----->
var request = require('request');
//set url
var url = 'http://localhost:8088/example';
//set header
var headers = {
'Authorization': 'Your authorization'
};
//set form data
var form = {first_name: first_name, last_name: last_name};
//set request parameter
request.post({headers: headers, url: url, form: form, method: 'POST'}, function (e, r, body) {
var bodyValues = JSON.parse(body);
res.send(bodyValues);
});
Just remember set method to POST in options. Here is my code
var options = {
url: 'http://www.example.com',
method: 'POST', // Don't forget this line
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'X-MicrosoftAjax': 'Delta=true', // blah, blah, blah...
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.97 Safari/537.36',
},
form: {
'key-1':'value-1',
'key-2':'value-2',
...
}
};
//console.log('options:', options);
// Create request to get data
request(options, (err, response, body) => {
if (err) {
//console.log(err);
} else {
console.log('body:', body);
}
});

Resources