I want to to bulk translocation and for that I uploaded the.csv file, its worked for me if I am using curl command but when I used its on node code its showing me error "file not uploaded"
Regarding to curl I am using that code which is working for me :-
curl -F 'data=#/var/www/html/achupload.csv' https://sandbox.usaepay.com/api/v2/bulk_transactions -H "Authorization: Basic X3llMVI3Mk9PdzFHOXBqcW1GaVp2NHJINjRc="
and this is my node code which are showing me error message :-
var request = require('request');
var headers = {
'Authorization': 'Basic X3llMVI3Mk9PdzFHOXBqcW1GaVp2NHJINjRc='
};
var dataString = '#/var/www/html/achupload.csv';
var options = {
url: 'url',
method: 'POST',
headers: headers,
data: dataString
};
console.log("options====",options);
function callback(error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
}
else{
console.log("notttttttttttt================",response.body);
}
}
request(options, callback);
How about this modification?
Modification points:
File content is retrieved with fs.createReadStream().
The file is sent as formData.
Modified script:
From:
var request = require('request');
var headers = {
'Authorization': 'Basic ###'
};
var dataString = '#/var/www/html/achupload.csv';
var options = {
url: 'url',
method: 'POST',
headers: headers,
data: dataString
};
To:
var fs = require('fs'); // Added
var request = require('request');
var headers = {
'Authorization': 'Basic ###'
};
var dataString = {data: fs.createReadStream('/var/www/html/achupload.csv')}; // Modified
var options = {
url: 'url',
method: 'POST',
headers: headers,
formData: dataString // Modified
};
Note:
In this modified script, 'Authorization': 'Basic ###' was used. Please be careful this. When you use this, please replace ### to yours.
References:
fs.createReadStream()
multipart/form-data (Multipart Form Uploads)
If this didn't resolve your issue, I apologize.
Related
Hello I have tried to use the instagram api to get a connection token. I first tested it on postman and this is what I did:
I used this link to make a request post to the instagram api:
https://api.instagram.com/oauth/access_token?client_id=clientid&client_secret=clientsecret&grant_type=authorization_code&redirect_uri=https://mysite/&code=thecode
The api gives me an error: Missing required field client_id
But when I set the content type to x-www-form-urlencoded everything works fine on postman.
So I tried to do the same thing in javascript with the node module request. I tried to do the same thing as on postman with the module but it does not work... Here is my code:
request(`https://api.instagram.com/oauth/access_token?client_id=clientid&client_secret=clientsecret&grant_type=authorization_code&redirect_uri=https://mysite/&code=` + code, {
method: 'POST',
headers: {"Content-Type": "x-www-form-urlencoded"}
}, (error, response, body) => {
console.log('body:', body)
})
As per MDN, the content type should be application/x-www-form-urlencoded
https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST
Update:
You should read the node doc : https://nodejs.dev/learn/making-http-requests-with-nodejs
Get method:
const https = require('https');
const options = {
hostname: 'api.instagram.com',
path: '/oauth/access_token?client_id=clientid&client_secret=clientsecret&grant_type=authorization_code&redirect_uri=https://mysite/&code=thecode',
method: 'GET',
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"Accept": "Accept-Encoding"
}
};
const req = https.request(options, (res) => {
// ...
});
Post method:
var headers = {
"Content-Type": "application/x-www-form-urlencoded",
"Accept": "Accept-Encoding"
};
var options = {
url: 'https://api.instagram.com/oauth/access_token',
method: 'POST',
headers: headers
};
var form = {
grant_type:'urn:ietf:params:oauth:grant-type:jwt-bearer',
client_id: 'id',
client_secret: 'secret'
redirect_uri : 'https://mysite/&code=thecode'
};
var request = https.request(options, function(response) {
// do stuff
});
request.write(querystring.stringify(form));
request.end();
I have been trying to figure out how to acquire an access token from Reddit API in Google Apps Script. I have below code written so far:
function main() {
var username = 'myredditusername';
var pwd = 'myredditpassword';
var client_id = 'myredditclientid';
var client_secret = 'myredditclientsecret';
var access_token_url = 'https://www.reddit.com/api/v1/access_token';
var api_url = 'https://oauth.reddit.com/';
var user_agent = 'MySideProjectUserAgent';
var data = {
'grant_type': 'password',
'username': username,
'password': pwd
};
var options = {
'method' : 'post',
'contentType': 'application/json',
'payload' : JSON.stringify(data),
'headers': {'User-Agent': user_agent},
// what do I enter here to pass my client_id and client_secret?
};
var resp = UrlFetchApp.fetch(access_token_url, options);
console.log(resp.getContentText());
}
Running the above code receives an error like below (not surprising because I still need to figure out how to pass in my client_id and client_secret):
Exception: Request failed for https://www.reddit.com returned code 401. Truncated server response: {"message": "Unauthorized", "error": 401} (use muteHttpExceptions option to examine full response)
When using curl, I was able to acquire the token successfully with this command:
curl -X POST -A 'KeywordTrackAgent' -d "grant_type=password&username=myredditusername&password=myredditpassword" --user 'client_id:client_secret' https://www.reddit.com/api/v1/access_token
From reaching around (example post), I figured that if I were to translate this curl request to a POST request, I'd need to add Authorization field to my headers parameter with the format like below:
function main() {
var username = 'myredditusername';
var pwd = 'myredditpassword';
var client_id = 'myredditclientid';
var client_secret = 'myredditclientsecret';
var access_token_url = 'https://www.reddit.com/api/v1/access_token';
var api_url = 'https://oauth.reddit.com/';
var user_agent = 'MySideProjectUserAgent';
var data = {
'grant_type': 'password',
'username': username,
'password': pwd
};
var options = {
'method' : 'post',
'contentType': 'application/json',
'payload' : JSON.stringify(data),
'headers': {
'User-Agent': user_agent,
// Below, I decided to encode my client_id and client_secret in base64 with the prefix 'Basic '
'Authorization': 'Basic clientIdAndClientSecretInBase64',
},
};
var resp = UrlFetchApp.fetch(access_token_url, options);
console.log(JSON.parse(resp.getContentText()));
}
I'm still receiving { error: 'unsupported_grant_type' }.
Could anyone--who has successfully fetched Reddit access token using JavaScript and preferably, using Google Apps Script--share some suggestion/insight on this? Thank you in advance for your answers!
I believe your goal as follows.
You want to convert the following curl command to Google Apps Script.
curl -X POST -A 'KeywordTrackAgent' -d "grant_type=password&username=myredditusername&password=myredditpassword" --user 'client_id:client_secret' https://www.reddit.com/api/v1/access_token
This curl command sends the data as the form data. And, the basic authorization is used. When these are reflected to the Google Apps Script, it becomes as follows.
Sample script:
In this script, your values are used.
function main() {
var username = 'myredditusername';
var pwd = 'myredditpassword';
var client_id = 'myredditclientid';
var client_secret = 'myredditclientsecret';
var access_token_url = 'https://www.reddit.com/api/v1/access_token';
var data = {
'grant_type': 'password',
'username': username,
'password': pwd
};
var options = {
'method': 'post',
'payload': data,
'headers': {
'Authorization': 'Basic ' + Utilities.base64Encode(`${client_id}:${client_secret}`),
},
};
var resp = UrlFetchApp.fetch(access_token_url, options);
console.log(JSON.parse(resp.getContentText()));
}
At this script, the request is same with the curl command.
Note:
In this script, it supposes that the values for authorizating are correct. Please be careful this.
Reference:
fetch(url, params)
I want to upload a binary file (images) to an api which accepts application/octet-stream. Unfortunately it seems angular wants to transform my request, which does not work obviously and results in
TypeError: key.charAt is not a function
My request looks like this:
var f = document.getElementById('file_picker').files[0],
r = new FileReader();
r.onloadend = function(e){
var fileData = e.target.result;
$http({
url: '.../upload/' + id,
method: 'PUT',
headers: {'Authorization': 'Bearer asdf',
'Content-Type': 'application/octet-stream'},
data: new Uint8Array(fileData),
transformRequest: []
})
})
r.readAsArrayBuffer(f);
This is my request via curl which works:
curl -i -X PUT -H "Authorization: Bearer asdf" -H "Content-Type: application/octet-stream" --data-binary #jpg.jpg https://.../upload/123
Any ideas? Thanks.
try this:
var fd = new FormData();
fd.append("file", fileObj);
$http({
method: "POST",
params: { 'forcecache': new Date().getTime() },
url: <yoururl>,
headers: {
"Content-Type": undefined
},
transformRequest: angular.identity,
data: fd
});
This is a working example on one of our projects. See http://www.uncorkedstudios.com/blog/multipartformdata-file-upload-with-angularjs/ for more details
Working solution:
var file = document.getElementById('file_picker').files[0],
reader = new FileReader();
reader.onload = function() {
var f = new Uint8Array(reader.result);
$http({
url: '...upload/,
method: 'PUT',
headers: {'Authorization': 'Bearer asdf',
'Content-Type' : undefined},
data: f,
transformRequest: []
});
};
reader.readAsArrayBuffer(file);
The problem is, we have a Data Mapping Interceptor configured, which converts all post and put requests to json. Ouch.
I try to make a GET request using Google Script. Sample code as below:
var username = "test#test.com";
var password = "12345";
var headers = {
"Authorization": "Basic "+ Utilities.base64Encode(username+":"+password)
};
var url = 'https://localhost/api/v2/get_sections/21';
var options = {
'method': 'get',
'contentType' : 'application/json',
'headers': headers
};
var response = UrlFetchApp.fetch(url, options);
I received an error
Request failed for https://localhost/api/v2/get_sections/21 returned code 400. Truncated server response: {"error":"Content-Type header missing (use Content-Type: application/json)"}
Is this the right way to make a get request?
The Content-Type is also a header, try :
var username = "test#test.com";
var password = "12345";
var headers = {
"Content-Type": "application/json",
"Authorization": "Basic "+ Utilities.base64Encode(username+":"+password)
};
var url = 'https://localhost/api/v2/get_sections/21';
var options = {
'method': 'get',
'headers': headers
};
var response = UrlFetchApp.fetch(url, options);
In my Project I send Multipart form-data from angular side to nodejs. the format of data i received is
{ name: 'customer.test.14',
email: 'test14#gmail.net',
website: 'www.google.com',
contact_name: 'Vijay',
contact_number: '+123456789022',
profile: 'Testing',
provider_category: 'exchange',
services_offered: 'Testing',
description: 'Test',
image:
[ { size: 1474,
type: 'image/png',
path: 'bc31dac580a7c2086f306fe0b9b5182d/',
basename: 'icon_dd_chart_grey.png' } ] }
I want to send data this to another api in nodejs. but api does not upload image.
here is my code
var request = require('request');
var api_url = global.common.base_url + 'vcard/1.0.0/visit_card/' + req.param('uuid') +'/';
console.log(req.body);
request({
url: api_url,
method: 'PUT',
headers: {
'Content-Type': 'multipart/form-data;',
'Authorization': 'Bearer '+req.cookies.apitoken
},
json: req.body,
}, function(error, response, body) {
if(response.statusCode == 200 && !error){
res.end(JSON.stringify(body));
}else{
res.send(response.statusCode, { error: body });
}
});
You can archive this using "Okhttp3". Please refer this video tutorial form reference and usage and documentation.
Eg: upload two bodies (json and a image) to a single endpoint at the same time:
const okhttp = require('okhttp');
var MimeBuilder = okhttp.MimeBuilder;
var Request = okhttp.Request;
var RequestBody = okhttp.RequestBody;
var RequestBuilder = okhttp.RequestBuilder;
var FormEncodingBuilder = okhttp.FormEncodingBuilder;
var MultiPartBuilder = okhttp.MultiPartBuilder;
let json = JSON.stringify({title:'test'});
var image = fs.readFileSync(path.resolve(__dirname, 'test.jpg'));
let mp_body = new MultiPartBuilder().addPart(RequestBody.create(json, 'Content-Type: application/json; charset=UTF-8'))
.addPart(RequestBody.create(image, new MimeBuilder().contentType('image/jpeg').contentTransferEncoding('binary').build()))
.type(MultiPartBuilder.FORMDATA).build();
new RequestBuilder().url('https://www.googleapis.com/upload/drive/v2/files?uploadType=multipart')
.header('Authorization', 'Bearer OAUTH2_TOKEN_HERE')
.POST(mp_body).buildAndExecute().then(console.log).catch(console.error);