Upload video to Cloudflare API - node.js

I am trying to upload some videos to Cloudflare Stream API. Here is official documentation and its example request using curl: https://developers.cloudflare.com/stream/uploading-videos/upload-video-file/
I am doing the request in Node.js
const uploadVideo = (video: Express.Multer.File): => {
const formData = new URLSearchParams();
formData.append('file', video);
let cloudflareResponse;
try {
cloudflareResponse = await axios.post(
`https://api.cloudflare.com/client/v4/accounts/${ACCOUNT_ID}/stream/copy`,
formData,
{
headers: {
Authorization: `Bearer ${API_KEY}`,
'Content-Type': 'multipart/form-data',
//'Tus-Resumable': '1.0.0',
//'Upload-Length': '600',
//'Upload-Metadata': 'maxDurationSeconds 600'
}
}
);
} catch (e) {
console.log('Error while trying to upload video to Cloudflare API ', e);
}
}
The commented Headers I took from this article, in which the request is done in Django and I tried to replicate it https://medium.com/#berman82312/how-to-setup-cloudflare-stream-direct-creator-uploads-correctly-802c37cbfd0e
The error I am getting is a 400 and here is some of the response
config: {
url: 'https://api.cloudflare.com/client/v4/accounts/...../stream/copy',
method: 'post',
data: 'file=%5Bobject+Object%5D',
headers: {
Accept: 'application/json, text/plain, */*',
'Content-Type': 'multipart/form-data',
Authorization: 'Bearer .....',
'Tus-Resumable': '1.0.0',
'Upload-Length': '600',
'Upload-Metadata': 'maxDurationSeconds 600',
'User-Agent': 'axios/0.21.1',
'Content-Length': 24
},
data: { result: null, success: false, errors: [Array], messages: null }
I am sure something is wrong in the request and hope someone could help me spot the mistake or suggest some modifications that might help. I have been stuck with this problem for hours and on Postman I am also getting a 400 response when trying to send with form-data.

Related

Why am I getting an empty body as response from HTTP request Noe.js

so I am trying to send a http request to a server and as response I should get the body where all the information I need is in. When I then try to .parseJSON() the body I get an exception telling me that my body is empty. There is no way that the body is really empty so there has to be a mistake in the code.
I can not give you the whole code because of passwords and stuff like that.
Code:
public addVehicle(): Promise<void>{
return new Promise<void>((resolve, reject) => {
const options = {
url: [URL],
method: "POST",
headers: {
'Content-Type': 'application/json',
'Authorization': [user/psw],
'token': [authToken]
},
body: JSON.stringify({
'vehicleID': vehicleID,
'externalID': externalID,
'brandID': vehicleBrandId,
'modelGroupID': vehicleModelId,
'typeName': typeName,
'segmentationID': vehicleSegmentationId,
'categoryID': vehicleCategoryId,
'fuelTypeID': vehicleFuelTypeId,
'transmissionTypeID': vehicleTransmissionTypeId,
'propulsionTypeID': vehiclePropulsionTypeId,
'registerationDate': registerationDate,
'powerKW': powerKW,
'description': description
})
}
let req = request.post(options, (err, res, body) => {
let rawAuth = JSON.parse(body);
console.log(body);
resolve();
})
})
}
Try removing the JSON.stringify().
I am assuming that your receiving API expects the fields in the body. Sending the data as string will hide the fields from the receiving API. It will just see one string object (not sure what the key will be tho).
const options = {
url: [URL],
method: "POST",
headers: {
'Content-Type': 'application/json',
'Authorization': [user/psw],
'token': [authToken]
},
body: {
'vehicleID': vehicleID,
'externalID': externalID,
'brandID': vehicleBrandId,
'modelGroupID': vehicleModelId,
'typeName': typeName,
'segmentationID': vehicleSegmentationId,
'categoryID': vehicleCategoryId,
'fuelTypeID': vehicleFuelTypeId,
'transmissionTypeID': vehicleTransmissionTypeId,
'propulsionTypeID': vehiclePropulsionTypeId,
'registerationDate': registerationDate,
'powerKW': powerKW,
'description': description
}
}

API Call with NodeJS signing with Oauth1 not working

I have a problem with my api call using NodeJS. I have no problem with postman, but when I run it with Node, server response is 401.
Here's the nodejs code:
var request = require("request");
var options = { method: 'GET',
url: 'https://api.cardmarket.com/ws/v2.0/output.json/products/find',
qs:
{ search: 'Salamangrande%25Loup%25Du%25Soleil',
idGame: '3',
idLanguage: '2' },
headers:
{ 'cache-control': 'no-cache',
Connection: 'keep-alive',
Cookie: 'PHPSESSID=m399v2el9635i3jq0e4did8f5k',
'Accept-Encoding': 'gzip, deflate',
Host: 'api.cardmarket.com',
'Postman-Token': '9b19a85d-8888-4f31-8d24-fe309a55bf76,4d8f4741-4b85-4d5e-85dc-8ac43ea5f56c',
'Cache-Control': 'no-cache',
Accept: '*/*',
'User-Agent': 'PostmanRuntime/7.19.0',
Authorization: 'OAuth realm="https%3A%2F%2Fapi.cardmarket.com%2Fws%2Fv2.0%2Foutput.json%2Fproducts%2Ffind",oauth_consumer_key="xxxxxxxxx",oauth_token="xxxxxxxxx",oauth_signature_method="HMAC-SHA1",oauth_timestamp="1579186959",oauth_nonce="vWUKBoTTkle",oauth_version="1.0",oauth_signature="ZD2TwzLVHqOjLm3u%2BWv%2FsQ8mdfs%3D"' } };
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(response.statusCode);
});
So basically here's my (perfectly working) .
Any idea what's wrong with the syntax or how to properly implement the oauth signature in the headers ?
HTTP 401 error means "unauthorized".
I don't think OAuth authorization is meant to be passed through the headers.
It is supposed to be something like :
var request = require("request");
url='https://api.cardmarket.com/ws/v2.0/output.json/products/find';
oauth = {
consumer_key: CONSUMER_KEY,
consumer_secret: CONSUMER_SECRET,
token: AUTH_TOKEN,
token_secret: TOKEN_SECRET,
signature_method : 'RSA-SHA1',
};
qs = {
search: 'Salamangrande%25Loup%25Du%25Soleil',
idGame: '3',
idLanguage: '2'
};
request.get({url:url, oauth:oauth, qs:qs, json:true}, function (e, r, product) {
console.log(product)
})
Check the request docs for more explanation on how to deal with OAuth in request.
(I strongly suggest using Axios instead of request, but that's up to you)

In what format should a fetch POST request be created to access the Imagga API?

I am building a mobile application using React-Native that recommends clothing to users. I am using Imagga's API to get the colors of the clothing while excluding the background. I have tried to make a POST request using fetch from analyzing the node.js code given in the documentation:
image_file_b64 = "" + image_file_b64
//Extracting the colors from the object
let response = await fetch('https://api.imagga.com/v2/colors', {
method: 'POST',
headers: {
'apiKey': '<PLACEHOLDER>',
'apiSecret': '<PLACEHOLDER>',
'Authorization': '<PLACEHOLDER>',
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
image_base64: image_file_b64,
extract_overall_colors: 0,
})
})
let responseJson = await response.json()
console.log(responseJson)
However, the only output that I have received is (what is logged on the last line):
Object {
"status": Object {
"text": "Please provide content for processing.",
"type": "error",
},
}
I've worked with someone from Imagga to solve this issue, but he wasn't familiar with react native. he suggested changing the content-type to "application/x-www-form-urlencoded" or "application/x-www-form-urlencoded;charset=UTF-8", but neither have worked.
I am fairly confident that the problem is from the way that I set up my fetch. If anybody is familiar with the Imagga API, can you please identify what in the code is wrong or the mismatch in formatting between what Imagga expects and what I am giving it that results in it not thinking that I have given it input. Thanks!
the fetch body is not correct, the Content-Type that you use is JSON, why you send the string. modify it as the following, and try it.
let response = await fetch('https://api.imagga.com/v2/colors', {
method: 'POST',
headers: {
'apiKey': '<PLACEHOLDER>',
'apiSecret': '<PLACEHOLDER>',
'Authorization': '<PLACEHOLDER>',
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: {
image_base64: image_file_b64,
extract_overall_colors: 0,
})
})
I read the official API, it gives the node.js example. you can according to it and modify. If the above code is not successful, you can change the content-type to formdata
let params = {
image_base64: image_file_b64,
extract_overall_colors: 0,
};
let formData = new FromData()
formdata.append('RequestData',JSON.stringify(params))
let response = await fetch('https://api.imagga.com/v2/colors', {
method: 'POST',
headers: {
'apiKey': '<PLACEHOLDER>',
'apiSecret': '<PLACEHOLDER>',
'Authorization': '<PLACEHOLDER>',
Accept: 'application/json',
'Content-Type': 'multipart/form-data',
},
body: formData)
})
this is the official api, and you can use postman software to test the request

"Body" of a post request always in unicode

If I make a POST request to a specific server using a Chrome plugin, I can see the "response body" comes back just fine in a JSOn format.
However when I try to do this with either "request" or "https.request", the "body" comes back as unicode which I can't seem to decipher. Anyone know how I can the body to come back as regular JSON, or how I could decipher this unicode? I tried a few stackoverflow solutions to decipher the unicode but no luck.
raw body:
��RPP�M-.NLOUR�RP�I,�K�P�,V��/QHL.�,KU��J�O�*─
�⎽�����wt�
⎽U��┬�>H ---
If I do this: JSON.stringify(body, null, 4)
"\┤001°�\␉\┤0000\┤0000\┤0000\┤0000\┤0000\┤0000\┤0000��RPP�M-.NLOUR�RP�I,�K�P�,V��/QHL.�,KU�\┤0001�J�O�*─\°�⎽����\┤000°�┬├\┤000␊�\°⎽U�\┤0005\┤0000�┬�>H\┤0000\┤0000\┤0000"
And here's the two code snippets I use to try and make POST requests:
request({
'url': 'https://api.nike.com/launch/entries/v2',
'method': 'POST',
'json': entriesPayload,
'headers': {
'authorization': authId,
"Accept": "application/json, text/plain, */*",
'Content-Type': "application/json;charset=utf-8"
},
},
...
and:
var options = {
hostname: 'api.nike.com',
port: 443,
path: '/launch/entries/v2',
method: 'POST',
json: entriesPayload,
headers: {
'authorization': authId,
"Accept": "application/json, text/plain, */*",
'Content-Type': 'application/json;charset=utf-8'
}
};
var req = https.request(options, (res) => {
res.on('data', (d) => {
process.stdout.write(d);
});
});
req.on('error', (e) => {
console.error(e);
});
req.write(postData);
req.end();
Also I get some real weird stuff happening after I make the request, in my IDE's logs. This is what shows up - it like translates everything into some different symbols (the last 3 lines are how I restarted my nodejs server).
"⎻⎺⎼├": 443,
"␤⎺⎽├┼▒└␊": "▒⎻␋.┼␋┐␊.␌⎺└",
"␤▒⎽␤": ┼┤┌┌,
"⎽␊▒⎼␌␤": ┼┤┌┌,
"─┤␊⎼≤": ┼┤┌┌,
"⎻▒├␤┼▒└␊": "/┌▒┤┼␌␤/␊┼├⎼␋␊⎽/┴2",
"⎻▒├␤": "/┌▒┤┼␌␤/␊┼├⎼␋␊⎽/┴2",
"␤⎼␊°": "␤├├⎻⎽://▒⎻␋.┼␋┐␊.␌⎺└/┌▒┤┼␌␤/␊┼├⎼␋␊⎽/┴2"
£,
"└␊├␤⎺␍": "POST",
"␤␊▒␍␊⎼⎽": π
"▒┤├␤⎺⎼␋≥▒├␋⎺┼": "B␊▒⎼␊⎼ ␊≤J␤␉G␌␋O␋JSU≥I1N␋I⎽I└├⎻ZCI6I┘␌2YWI1NT␤┐LWM┬ZTM├NGV␤Y␋05MT┌┘LTJ┐Y┘A3Y┘F┘N2N␤MHN⎻Z≤J9.␊≤J0␌┼V≥␍CI6MTA┬LCJ⎻YXQ␋O┘E1NDM2N≥␌┬ODA⎽I└V4␌CI6MTU0M≥Y4MDY4MC┬␋▒XN≥I┘⎺␋␉2F1␍G±≤YWN┘I␋┬␋▒┼R⎻I┘⎺␋ZGV␋MTZ┘M2Q├YT±│OS00OTE3LWF␤MD┐├NWV␤N≥R└M┘U┬MWM4I␋┬␋␉GF0I┘⎺│NTQ≥N┘␌3MD±┬LCJ␤␍WQ␋O␋J┘␉20┤␉└┌⎼ZS5┐▒W␍⎻␍GF⎽I␋┬␋␌3V␋I┘⎺␋Y29├L└5⎻▒2U┤Y29├␉WV≤Y2U┤␌25⎼␌┼M┤␍2V␋I␋┬␋␌2J0I┘⎺␋␉└┌⎼ZT⎻␤␌HA␋LCJ≥Y3A␋O┌⎽␋Y29├␉WV≤Y2U␋XS┬␋␌HJ┤I┘⎺␋M└I≥M≥J┐Y└U├MWE1Y≤00ZWJ┐LT┐0Z└Y├MGU┬N≥V┘OGV┘NGQ│I␋┬␋␌HJ0I┘⎺␋␉└┌⎼ZT⎻┬␉HV≥I┼0.I┴▒┘└U2W≤␉__┬AD└J±⎻Z≥␉␋-VVUV┘H⎽⎼EI├┼T┌␍1I9°┬OSL▒┬┤8≥0Z3┐C␍␊G⎽␊O≤│≥␌␉3RB┌GKXV┤SDRDH±IYZ␉H1X⎼5␉Q-┼R≥└┬I␤│␉M0─I⎺R┤␋␍␤▒I␋├NC␍⎺G±6⎺XQ␋°R┴W5␍⎺SZ┼⎻4YR2TN6U␍9Q≥⎻61NS⎺⎻F␌2V13NJ└0P7│K5-09⎻▒1│6P␍M≤┼⎽IWF─␤II⎼G≤K┘HO⎻BV└┌┤␋A≥°┼AF┤K1GC┌ZGD⎺TC␋8⎻JY_⎺HI-E8D±M┐O4KSN⎻H97KLHO-┴Z│2┬YLJ2°␉0⎼F┐D≤≤└A␍K⎼9┴┬┤9┼│XF␍⎼≥⎽┘22≤39KD⎻-⎽⎻R┐I⎺MD2▒└␋┼L1CA│8─-␉L│DY└┬GQ02C├I0─┘±",
"A␌␌␊⎻├": "▒⎻⎻┌␋␌▒├␋⎺┼/┘⎽⎺┼, ├␊│├/⎻┌▒␋┼, */*",
"C⎺┼├␊┼├-T≤⎻␊": "▒⎻⎻┌␋␌▒├␋⎺┼/┘⎽⎺┼;␌␤▒⎼⎽␊├=┤├°-8",
"␌⎺┼├␊┼├-┌␊┼±├␤": 575
£
£
£
[┼⎺␍␊└⎺┼] ⎼␊⎽├▒⎼├␋┼± ␍┤␊ ├⎺ ␌␤▒┼±␊⎽...
[┼⎺␍␊└⎺┼] ⎽├▒⎼├␋┼± ◆┼⎺␍␊ ▒⎻⎻.┘⎽◆
E│⎻⎼␊⎽⎽ ⎽├▒⎼├␊␍ ⎺┼ ⎻⎺⎼├ 3000
The response body is not unicode encoded, but GZIP encoded (compressed data). We can check if a response is compressed with the Content-Encoding header:
var encoding = res.headers['content-encoding'];
https doesn't unzip the response body automatically like a browser does, and so you get all those strange characters instead of a JSON string. However, we can use the built-in zlib library and decdode the response to a string.
const https = require('https');
const zlib = require('zlib');
var options = {
hostname: 'api.nike.com',
port: 443,
path: '/launch/entries/v2',
method: 'POST',
headers: {
'Authorization': 'my-token',
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json;charset=utf-8'
}
};
var data = JSON.stringify({});
var req = https.request(options, (res) => {
var encoding = res.headers['content-encoding'];
console.log('code:', res.statusCode);
console.log('encoding:', encoding);
deflate = zlib.createGunzip();
res.pipe(deflate);
deflate.on('data', (chunk) => {
console.log('data: ' + chunk.toString());
});
});
req.on('error', (e) => {
console.error(e);
});
req.write(data);
req.end();
The chrome plugin that you're using to POST is probably setting the content-type correctly, while your regular request from your server isn't.
Can you change your request so it includes
request({
'url': externalUrl,
'method': 'POST',
'json': entriesPayload,
'Content-Type': 'application/x-www-form-urlencoded'
});

Uploading a file using "fetch" in reactJS

Uploading a file using "fetch" in reactjs
I am trying to upload a file using ReactJS.
handleUploadfile = (event) => {
event.preventDefault();
const data = new FormData();
data.append('photo',event.target.files[0] );
data.append('name', 'Test Name');
data.append('desc', 'Test description');
fetch("http://localhost:3001/todo/upload", {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded'
},
body: data
}).then((response) => {
return response.text();
})
}
For some reason I am not able read the files at nodejs(+multer) server using:
req.files
which shows "undefined" at post router.
Finally I found the solution
I had to remove the 'Content-Type' from headers section and it worked out in nodejs using multer.
Using the "multipart/form-data"
'Content-Type': 'multipart/form-data'
requires us to set boundaries and hence it is throwing error at nodejs "Error: Multipart: Boundary not found"
Using the "application/x-www-form-urlencoded"
'Content-Type': 'application/x-www-form-urlencoded'
I am getting the req.body filled but as string but not able to access the individual values.
Hence final solution is removal of 'Content-Type'

Resources