In new Zapier UI, I used to do below..
return z.request(options).then(response => {
response.throwForStatus();
const results = z.JSON.parse(response.content);
let attachmentArray = [];
attachmentArray = results.data.map(function(result) {
let attachment = {};
attachment.id = result.attachment_id;
let file_url = options.url + `/${attachment.id}`;
attachment.url = file_url;
attachment.file = z.dehydrateFile(file_url, {
method: "GET",
headers: { Authorization: `Bearer ${bundle.authData.access_token}` }
});
return attachment;
});
return attachmentArray;
});
This is my code to provide a trigger. Currently, it throws
Error: You must pass in a function/array/object. We got string instead.
David here, from the Zapier Platform team. That error comes from this line, which is responsible for finding methods on your root App object. We've actually got a test covering that exact case here.
The offending code doesn't seem to be in the sample you provided above, but take a look at anywhere you're calling dehydrate('some str') or appTester('some string')
Related
I am able to upload a file on android to a C# web api, using nativescript-camera with nativescript-background-http.
I set the params as follows:
var params = [{ name: "image", filename: fileUri, mimeType: 'application/octet-stream' }];
...
And send the request:
let request = {
url: this.API_URL + "/UploadOctetFile",
method: "POST",
headers: {
"Authorization": accessTokenJson,
"Content-Type": "application/octet-stream",
"File-Name": imageName
},
description: "{ 'uploading': " + imageName + " }"
};
return this.session.multipartUpload(params, request);
In android the fileUri is returned in a fairly straight forward manner:
takePictrue.then((imageAsset: ImageAsset) => {
Then imageAsset.android has the file uri that is needed to send the image. However, for ios, imageAsset.ios is a PHAsset. To get the file URI, I use the following code:
let manager = PHImageManager.defaultManager()
let options = new PHImageRequestOptions();
options.resizeMode = PHImageRequestOptionsResizeMode.Exact;
options.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
manager.requestImageForAssetTargetSizeContentModeOptionsResultHandler(imageAsset.ios, { width: 2048, height: 1536 }, PHImageContentModeAspectFill, options, function (result, info) {
let srcfilePath = info.objectForKey("PHImageFileURLKey").toString();
...
});
In the above: srcfilePath (which I pass as fileUri) is: file:///var/mobile/Media/DCIM/101APPLE/IMG_1902.JPG
The image name is then IMG_1902.JPG
However, this uploads an empty file. I'm guessing that I need to change the fileUri or perhaps I should be using a different method to: requestImageForAssetTargetSizeContentModeOptionsResultHandler.
I have tried the solution suggested here to do:
let fileUri = image.fileUri.replace("file://","");
and I've tried changing the mime type "mimeType":"image/jpg".
Any ideas are much appreciated.
Sam, this might help. I did the following to handle an iOS user selecting a photo from their gallery for use later in the app (Android is simple and straightforward like in your case, but iOS returns a PHAsset):
import { ImageSource } from "image-source";
import { Image } from "tns-core-modules/ui/image";
import { path, knownFolders } from "tns-core-modules/file-system";
//iOS user picks photo...
const iosImg = new ImageSource();
iosImg.fromAsset(myPHAsset).then(imsr => {
this.counter += 1; //class property to allow unique filenames
const folder = knownFolders.documents();
const path2 = path.join(folder.path, `Image${this.counter}.jpg`);
const saved = imsr.saveToFile(path2, "jpg");
const img = new Image();
img.src = path2;
this.data.changeImage(img); //Ng service to allow use of image in other components
});
Links: {N} docs
{N} imagepicker #197
{N} imageUpload code
I tried to change the existing angularjs library to angular2 for my need. http.post method in the below code throws TypeError {} as exception. Someone please help as i am stuck on this.
login() {
return new Promise((resolve, reject) => {
if(typeof jsSHA !== "undefined") {
var signatureObj = (new OauthUtility()).createSignature("POST", this.magentoOptions.baseUrl+"/oauth/initiate", this.oauthObject, {oauth_callback: "http://localhost/callback"}, this.magentoOptions.clientSecret, null);
let headersInitiate = new Headers();
headersInitiate.append('Authorization',signatureObj.authorization_header);
headersInitiate.append('Content-Type','application/x-www-form-urlencoded');
let url = this.magentoOptions.baseUrl + "/oauth/initiate";
let callback = "oauth_callback=http://localhost/callback";
try{
this.http.post(url, callback,{headers: headersInitiate})
.subscribe(
(result) => {
console.log("i am inside");
var rParameters = (result).split("&");
.....
}
catch(Exception){
console.log(Exception)
}
You should try something like that:
var signatureObj = (new OauthUtility()).createSignature("POST",
this.magentoOptions.baseUrl+"/oauth/initiate", this.oauthObject,
{oauth_callback: "http://localhost/callback"},
this.magentoOptions.clientSecret, null); let headersInitiate = new Headers();
headersInitiate.append('Authorization',
signatureObj.authorization_header);
headersInitiate.append('Content-Type',
'application/x-www-form-urlencoded');
let url = this.magentoOptions.baseUrl + "/oauth/initiate";
let payload = ' ... ';
this.http.post(url, payload,{headers: headersInitiate})
.subscribe(
(result) => {
console.log("i am inside");
var rParameters = (result).split("&");
(...)
});
Here are the comments I would have on your code:
The second parameter of the post method should be a string corresponding to the payload not a callback. I see from your headers that you want to send url-encoded form, so you need to create it by your own
The try catch isn't necessary since executing an HTTP is asynchronous and errors can be "catched" within the second parameter (another callback) of the subscribe method.
You don't need at all a promise. For HTTP, Angular2 uses observables under the hood. They target asynchronous processing as well.
After fixing all of this, I think that you won't have error anymore...
Hope it helps you,
Thierry
I found to stuck even after proceeding with the above all steps. The complete solution is as follows.
Remove try catch block and promise as suggested by Thierry.
Use dependency injection of http inside the constructor as follows to define http.
import {Http,HTTP_PROVIDERS,Headers} from 'angular2/http';
import {Injector} from "angular2/core";
constructor() {
var injector = Injector.resolveAndCreate([HTTP_PROVIDERS]);
this.http = injector.get(Http);
}
Using the Node integration provided by cloudinary_npm, I'm getting the following message back when I try to upload:
{ error: { message: 'Invalid Signature t7233823748278473838erfndsjy8234. String to sign - \'timestamp=1439054775\'.', http_code: 401 } }
I retrieve then pass my image to the backend like this:
$scope.previewFile = function() {
var file = document.querySelector('input[type=file]').files[0];
var reader = new FileReader();
if (file) {
reader.readAsDataURL(file);
} else {
preview.src = "";
}
reader.onloadend = function () {
base64img = reader.result;
preview.src = base64img;
console.log(base64img);
};
};
$scope.submitPic = function() {
$http.post('http://localhost:3000/story/pic', {img: base64img})
.success(function(data){
preview.src = "";
})
.error(function(err){
console.log(err);
});
};
Then in the back, I have the following configuration and routes, both straight from the docs:
var cloudinary = require("cloudinary");
var CLOUD_API_SECRET = require("../constants.js");
cloudinary.config({
cloud_name: 'some_cloud',
api_key: '63789865675995',
api_secret: CLOUD_API_SECRET
});
router.post('/pic', function(req, res, next) {
var img = req.body.img;
cloudinary.uploader.upload(img, function(result) {
});
res.status(200).send('ok');
});
Does anyone recognize what I might be doing wrong? I've been troubleshooting this for hours. I'm at a dead end.
make sure you have placed your cloudinary secret inside a ''(quote/inverted comma).make sure the resulting statement should mean :
var CLOUD_API_SECRET ='some_cloudinary_secret_xxx';
check this value in the js file from where you are fetching this value.
From Java level I fixed this issue by changing the time zone to America/New_York time:
Long time = new Long(System.currentTimeMillis() );
SimpleDateFormat sdf = new SimpleDateFormat();
sdf.setTimeZone(TimeZone.getTimeZone("America/New_York"));
Date date = new Date(sdf.format(new Date(time)));
long utcDateInMilliSeconds = date.getTime();
params.put("timestamp", new Long(utcDateInMilliSeconds/1000));
I had this very same error running similar code route on nodejs using cloudinary's sdk.
The issue turned out to be a typo within my API_SECRET.
Like Jeremy said, It's mostly typo or white space in your API secret.
Try to use your API secret directly in the configuration (not via variable)
I have problem with autocomplete. The code below is returnig me
["foo#foo.com","bar#bar.com"]
$('.autocomplete').keyup(function() {
tid = $(this).attr('id')
$(this).autocomplete({
source: function (req, resp){
$.ajax(
{
url: "autocompl.asp",
data:$("#msgForm").serialize() + "&field="+tid ,
success : function( resp ) {
return resp
}
})
}
});
});
But the suggestions don't appear. It worked for me when I have called autocomplete without any extra parameters.
Any clue?
Thanks in advance
Magda
Note that one of your parameters for the source function is resp, and you're using another resp afterwards. I think you need to use the first resp to send the response object back.
I'm using this as well and this works for me (Instead of sending an array of values, I'm sending an array of objects with two attributes, but I don't think it's mandatory).
id
label
so the code inside the ajax success should look something like this (my data variable is your second resp variable, a different name to avoid mixup):
success: function(data) {
for (i in data) {
a = {}
a.id = data[i]
a.label = data[i]
options.push(a)
}
resp(options)
}
I'm currently developing a Firefox add-on(using https://addons.mozilla.org/en-US/developers/docs/sdk/1.0/ ) that consumes an API where the return data is in xml.
My problem is that I need to parse the returned data, and would like to do that using a xml object.
Since the request module only supports JSON and Text ( https://addons.mozilla.org/en-US/developers/docs/sdk/1.0/packages/addon-kit/docs/request.html#Response ) I need to convert the response.text to XML.
The code looks like this:
var Request = require('request').Request
.......
var req = Request({
url: https://to-the-api.com,
content: {
op: 'get-the-data-op',
password: "super-sec",
user: "username"
},
onComplete: function (response) {
dataAsText = response.text;
console.log("output: " + dataAsText);
}
});
req.post();
I have tried to user (new DOMParser).parseFromString(response.text, 'text/xml') but unfortunately it just fails with a error like ReferenceError: DOMParser is not defined
The question is if anyone of you guys have been able to create a Xml object inside a Firefox add-on, and if so, how?
Looks like the capability to parse response as xml was present, but has been removed. check out this bugzilla reference
Can't you use a normal XMLHttpRequest if you want to process the response as XML?
If DOMParser is unavailable you can try E4X:
var xml = new XML(response.text);
alert(xml.children().length());
You want to use the XMLHttpRequest object to handle your xhr request. Then when you get a response back access the responseXML object of the request variable. In the responseXML you'll have the documentElement and can use the querySelectorAll or querySelector to find elements you want. In each element you want just grab the textContent you need.
Here's an example to get you going (this looks for the 'xmls' element in the response):
var request = new require("xhr").XMLHttpRequest();
request.open('GET', 'https://to-the-api.com', true);
request.onreadystatechange = function (aEvt) {
if (request.readyState == 4) {
if(request.status == 200) {
var xmls = request.responseXML.documentElement.querySelectorAll("xmls");
for (var i = 0; i < xmls.length; i++) {
console.log("xml", i, xmls[i], xmls[i].textContent);
}
}
else {
console.log('Error', request.responseText);
}
}
};
request.send(null);