Posting (by streaming?) with mikeal request - facebook

I'm trying to post a photo using mikeal request library, but the post comes emp
request = require('request')
fs = require("fs")
fs.createReadStream('zebra.jpg').pipe(request.post('http://localhost:2000'))
(on localhost:2000 I've got a simple echo for now)
Now, this works but I want to pass additional parameters using standard POST format.
What I'm actually trying to do is to post an image to Facebook via API, which means I'd like to include a title and possibly some more fields.
If streaming is not the right approach (although I see many benefits such as getting away without temporary files and buffers), what would be the right one?
Thanks for ideas.
UPD:
I've got this far:
fs.createReadStream('zebra.jpg').pipe(graph.post('418533674856800/photos',
{message:"I'm a new API photo!", name:"API Photo",privacy:{value:"EVERYONE"}},
function(err, res) {
console.log(res);
}));
but it returns
dest.on('drain', ondrain);
^
TypeError: Object #<Graph> has no method 'on'
at [object Object].pipe (stream.js:52:8)
at Request._callback (c:\My Stuff\Creatiff\PRAGmatiki\Web-node.js\postaspage.js:66:36)
at Request.callback (c:\My Stuff\Creatiff\PRAGmatiki\Web-node.js\node_modules\request\main.js:119:22)
at Request.<anonymous> (native)
at Request.emit (events.js:70:17)
at Request.<anonymous> (c:\My Stuff\Creatiff\PRAGmatiki\Web-node.js\node_modules\request\main.js:521:16)
at Request.emit (events.js:67:17)
at IncomingMessage.<anonymous> (c:\My Stuff\Creatiff\PRAGmatiki\Web-node.js\node_modules\request\main.js:483:14)
at IncomingMessage.emit (events.js:88:20)
at HTTPParser.parserOnMessageComplete [as onMessageComplete] (http.js:130:23)
Is this happening because I'm streaming? Any help please!

var path = require('path'),
mime = require('mime');
request({
url: 'http://localhost:2000',
headers: {
'content-type' : 'multipart/form-data'
},
method: 'POST',
multipart: [{
'Content-Disposition' : 'form-data; name="inputname"; filename="' + path.basename('zebra.jpg') + '"',
'Content-Type' : mime.lookup('zebra.jpg'),
body: fs.readFileSync('zebra.jpg')
},{
'Content-Disposition' : 'form-data; name="input[array]"; filename="' + path.basename('zebra1.jpg') + '"',
'Content-Type' : mime.lookup('zebra1.jpg'),
body: fs.readFileSync('zebra1.jpg')
},{
'Content-Disposition' : 'form-data; name="input[array]"; filename="' + path.basename('zebra2.jpg') + '"',
'Content-Type' : mime.lookup('zebra2.jpg'),
body: fs.readFileSync('zebra2.jpg')
},{
'Content-Disposition' : 'form-data; name="text"',
body: "text input"
}]
},
function(err, res, body){
});

I don't know what graph is (doesn't appear in mikeael's documentation), but it doesn't implement the Stream interface so can't be used with pipe().
To send multiple parts in a POST you need to use a request of type multipart/form-data. The latest version of mikeal/request has experimental support for this (with examples). Other modules also support it (needle for example, though stream support was a little lacking last time I looked).

Related

Creating new document with Firestore REST API and Local Emulator Suite for Integration Test, Returning Error 400: Problem with Request Body?

I recently posted a question regarding creating a document in a collection in the local emulator suite using a HTTP Post Request with Axios.
Creating new document with Firestore REST API and Local Emulator Suite, Returning Error 404: Problem with Path Parameter
My previous error was a 404 error with the URL path parameter. Since making changes to that, now I’m receiving a 400 error. The following is the code:
First, using a post request to create an authenticated user ID token and storing that in a variable. No issues here.
//HTTP Post Request to create an auth ID, storing ID Token in variable
const createUserResponse = await axios.post(createUserInstance.url, createUserInstance.data, createUserInstance.config);
const userIdToken = createUserResponse.data.idToken;
const userLocalId = createUserResponse.data.localId;
console.log(userIdToken);
console.log(userLocalId);
Second, writing the request body. I’ve modified the URL which works now. I’ve also re-modified the data body to make sure it’s in the correct format.
Wondering if the issue is in:
the way I’ve written the query parameters (do I need to specific the new document name? is the API key the problem?)
the formatting of the data request body : according to the documentation a new document is automatically generated. I’d presume fields would be read as containing the key-value pairs to include in the document fields.
the formatting of the headers. I’ve checked and re-checked this. My userIDToken contains a string
//create a document in the user collection
//request body
const createDocumentInstance : createPostRequest = {
url: 'http://localhost:8080/v1beta1/projects/okane-crud-dev/databases/(default)/documents/test?key=<API_KEY>',
data: {
'fields': {
'localId': 'hello',
}
},
//directly pasted IdToken as using the variable resulted in problem with ' ' error
config: {
'headers':
{
'Content-Type': 'application/json',
'Authorization': `Bearer ${userIdToken}`,
}
}};
To make sure of what I was looking at, I logged the entire request in my console. This is what it looks like.
console.log
{
url: 'http://localhost:8080/v1beta1/projects/okane-crud-dev/databases/(default)/documents/test?key=AIzaSyCQSnirvajGL5Uok34OgEn7tF1S_tp5sa0',
data: { fields: { localId: 'hello' } },
config: {
headers: {
'Content-Type': 'application/json',
Authorization: 'Bearer eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJlbWFpbCI6Im15ZW1haWxAZW1haWwuY29tIiwiZW1haWxfdmVyaWZpZWQiOmZhbHNlLCJhdXRoX3RpbWUiOjE2NjU0NTQ2MDgsInVzZXJfaWQiOiI1Vmt3TUtRc1k0THJRTkRWaXpFYmdnYnExOVNyIiwiZmlyZWJhc2UiOnsiaWRlbnRpdGllcyI6eyJlbWFpbCI6WyJteWVtYWlsQGVtYWlsLmNvbSJdfSwic2lnbl9pbl9wcm92aWRlciI6InBhc3N3b3JkIn0sImlhdCI6MTY2NTQ1NDYwOCwiZXhwIjoxNjY1NDU4MjA4LCJhdWQiOiJva2FuZS1jcnVkLWRldiIsImlzcyI6Imh0dHBzOi8vc2VjdXJldG9rZW4uZ29vZ2xlLmNvbS9va2FuZS1jcnVkLWRldiIsInN1YiI6IjVWa3dNS1FzWTRMclFORFZpekViZ2dicTE5U3IifQ.'
}
}
}
Finally, making the post request on Axios. Exact same syntax as my previous post request.
//Post Request to create a document
const createDocument = await axios.post(createDocumentInstance.url, createDocumentInstance.data, createDocumentInstance.config);
const docReference = createDocument.data;
console.log(docReference);
When running this, the following error is returned:
{
message: 'Request failed with status code 400',
name: 'Error',
description: undefined,
number: undefined,
fileName: undefined,
lineNumber: undefined,
columnNumber: undefined,
stack: 'Error: Request failed with status code 400\n' +
' at createError (/Users/georgettekoo/Documents/Code/Okane/Okane-Firebase-Backend-Deprecated/functions/node_modules/axios/lib/core/createError.js:16:15)\n' +
' at settle (/Users/georgettekoo/Documents/Code/Okane/Okane-Firebase-Backend-Deprecated/functions/node_modules/axios/lib/core/settle.js:17:12)\n' +
' at IncomingMessage.handleStreamEnd (/Users/georgettekoo/Documents/Code/Okane/Okane-Firebase-Backend-Deprecated/functions/node_modules/axios/lib/adapters/http.js:293:11)\n' +
' at IncomingMessage.emit (node:events:539:35)\n' +
' at endReadableNT (node:internal/streams/readable:1344:12)\n' +
' at processTicksAndRejections (node:internal/process/task_queues:82:21)',
config: {
transitional: {
silentJSONParsing: true,
forcedJSONParsing: true,
clarifyTimeoutError: false
},
adapter: [Function: httpAdapter],
transformRequest: [ [Function: transformRequest] ],
transformResponse: [ [Function: transformResponse] ],
timeout: 0,
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: -1,
maxBodyLength: -1,
validateStatus: [Function: validateStatus],
headers: {
Accept: 'application/json, text/plain, */*',
'Content-Type': 'application/json',
Authorization: 'Bearer eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJlbWFpbCI6Im15ZW1haWxAZW1haWwuY29tIiwiZW1haWxfdmVyaWZpZWQiOmZhbHNlLCJhdXRoX3RpbWUiOjE2NjU2MzAwMTUsInVzZXJfaWQiOiJEMTBoblpsek9nQWR0ZlJlNm1VUDBOY2ZtNm5pIiwiZmlyZWJhc2UiOnsiaWRlbnRpdGllcyI6eyJlbWFpbCI6WyJteWVtYWlsQGVtYWlsLmNvbSJdfSwic2lnbl9pbl9wcm92aWRlciI6InBhc3N3b3JkIn0sImlhdCI6MTY2NTYzMDAxNSwiZXhwIjoxNjY1NjMzNjE1LCJhdWQiOiJva2FuZS1jcnVkLWRldiIsImlzcyI6Imh0dHBzOi8vc2VjdXJldG9rZW4uZ29vZ2xlLmNvbS9va2FuZS1jcnVkLWRldiIsInN1YiI6IkQxMGhuWmx6T2dBZHRmUmU2bVVQME5jZm02bmkifQ.',
'User-Agent': 'axios/0.24.0',
'Content-Length': 30
},
method: 'post',
url: 'http://localhost:8080/v1beta1/projects/okane-crud-dev/databases/(default)/documents/test?key=AIzaSyCQSnirvajGL5Uok34OgEn7tF1S_tp5sa0',
data: '{"fields":{"localId":"hello"}}'
},
code: undefined,
status: 400
}
Not sure what I'm missing and where the issue is. Does anyone have any hints?

500 error when trying to create page using REST API

I'm currently using Confluence server and I'm currently getting a 500 error when I try to create a new page using the REST API. I am currently using an HTML macro that makes GET & POST requests using the Fetch API. I currently have no issues when making GET requests, only issues with POST requests.
I tried researching the error and saw someone mention that they fixed it by turning off collaborative editing in the space, but in my case that is not an option. Anyone have an idea of what is causing this error?
function createPage() {
let url = "http://exampledomain:8090/confluence/rest/api/content/"
fetch(url, {
method: 'POST',
headers: {
'Authorization': 'Basic USER:PASS',
'Content-Type': 'application/json',
},
data: {
'type': 'page',
'title': "New Page",
'ancestors': [{ 'id': 97059352 }], // parent page id
'space': { 'key': "EXAMPLE_SPACE" },
'body': {
'storage': {
'value': "<h1>New Page!</h1>",
'representation': 'storage',
}
},
}
})
.then(response => console.log(response))
.catch(err => console.log(err.message))
}
I see invalid data structure:
'representation': 'storage', <== extra comma
}
}, <== another extra comma
}
Also double check with your programming language that you can use single quotes (') and that they are correctly transformed into double quotes ("). JSON (Jira REST API) accepts only double quotes for keys and string values.

get token from spotify API using axios, error 404

I`m trying to get the token from the spotify API, I use axios. I use the example given by the API as a guide, but give me the error 404
export const getToken = code => async dispatch => {
const responseToken = await axios.post({
url: "https://accounts.spotify.com/api/token",
form: {
grant_type: "authorization_code",
code,
redirect_uri
},
headers: {
'Authorization': 'Basic ' + (new Buffer(client_id + ':' + client_secret).toString('base64'))
},
json: true
})
console.log(responseToken);
The first line is because I`m using redux,I just wanted you to see that it was a asinc method.
I have being all day trying to fix this, I don`t have more ideas of how to solve this
Try changing
form: {
grant_type: "authorization_code",
code,
redirect_uri
}
to
data: JSON.stringify({
grant_type: "authorization_code",
code,
redirect_uri
})
You want to send it in the request body, hence "data", that's how you define it in axios.
Also, I don't think you need json: true
EDIT:
Pretty sure you have to add 'content-type': 'application/x-www-form-urlencoded;charset=utf-8' to the headers as well.

Paypal Api is not working for Tizen tv

Paypal Rest Api is not working for Tizen tv while its working fine on rest client.
Neither success nor failure function is called in Tizen tv.
Changed the url other than paypal its working fine. Also tried with ajax no changes found.
here is the sample code for it.
Get:
var request = $http({
method : "get",
url : "https://api.sandbox.paypal.com/v1/payments/payment",
headers : {
"Content-Type" : "application/json",
"Authorization": "Bearer A101.FfLKjOmGx-80JU9h9ACDqrm0-dSg5pvlUsMnz2Slsb9hbSZSNQXQ7c653uc0XEYS.dd1D0romSBOfYq_Q7dIh6KEQg0O"
}
});
request.then(function(response){
console.log(response);
},function(error){
console.log(error);
});
Post :
var request = $http({
method : "POST",
url : 'http://api.sandbox.paypal.com/v1/oauth2/token',
data : 'grant_type=client_credentials',
headers : {
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/x-www-form-urlencoded',
'Accept-Language': 'en_US',
"Authorization": "Basic QWVRWnpOanM5UGdrQVdyb1VkbjktZ1lhcmNzNUxST2hSN2QyN1VTLTAyb0lXNy1pcmhyMUFkWXhLdkpoY1Q5Y0JoUXlxeHJDZW5MV2JXQjI6RUR4Q3pwbmRkRHBHSVI4SFo2TUR6dzkxYjR6enZndXgwc1hDSFhfU0c5c0pmOHFDNmg4NWd3S3ctTktIbW1ObXNtMFZpT0FQOU84WHREZFc="
}
});
request.then(function(response){
console.log(response);
},function(error){
console.log(error);
});
This API guide in Samsung D forum holds some examples that may help your query regarding Paypal.
Samsung D forum API guide : https://www.samsungdforum.com/TizenGuide/tizen4791/index.html
If you still face issues, You may try posting in the SamsungDForum
SamsungDForum Tizen TV: https://www.samsungdforum.com/SamsungDForum/ForumDashBoard
Thank you.

Google Docs API: cannot set document title

I am trying to upload a file using Node and Google Docs REST API. I can upload the file just fine if I don't include the metadata, but it will always be uploaded as 'Untitled'.
But when I include the meta data I get the following error after sending my atom data and attempting to continue with the file upload:
ParseException - Content is not allowed in prolog
This is my first request to create an upload session and get a resumable-media-link
var meta = '<?xml version="1.0" encoding="UTF-8"?>'
meta+= '<entry xmlns="http://www.w3.org/2005/Atom" xmlns:docs="http://schemas.google.com/docs/2007">'
meta+= '<category scheme="http://schemas.google.com/g/2005#kind" term="http://schemas.google.com/docs/2007#document"/>'
meta+= '<title>Test</title></entry>'
var options = {
host: 'docs.google.com',
path: '/feeds/upload/create-session/default/private/full',
method: 'POST',
headers: {
'Host' : 'docs.google.com',
'Content-Length' : meta.length,
'Content-Type': 'application/atom+xml',
'GData-Version' : 3,
'Authorization' : 'GoogleLogin auth=' + authToken,
'X-Upload-Content-Type' : 'application/msword',
'X-Upload-Content-Length' : 31232
}
}
var req = https.request(options, function (res) {
// make 2nd request
});
req.end(meta);
This is what my 2nd request looks like after getting the resumable-media-link
var options = {
host: 'docs.google.com',
path: resumableMediaLink,
method: 'PUT',
headers: {
'Content-Length': data.length,
'Content-Type': 'application/msword',
'Content-Range': 'bytes 0-' + (data.length-1) +'/'+ data.length
}
}
var req = https.request(options, function (res) {
res.on('data', function (chunk) {
// ...
});
});
req.write(data);
req.end();
It seems like I am sending the atom data incorrectly. Any ideas of what I could be doing wrong?
I figured out what I was doing wrong.
I needed to set the 'Slug' header in the first POST request to initiate a resumable session.
I had it in the following request.