Error when parsing array with OpenLayers and Protocol.HTTP() - javascript

I'm trying to send a JSON file to my Node.js app via Protocol.HTTP. The file is correctly sent, but I can't access to an array. Here is the relevant code :
Client side
(...)
var vectorProtocol = new OpenLayers.Protocol.HTTP({
url: '/getcoords',
format: vectorFormat,
readWithPOST: true,
params: {
"code_company": "8501",
"data_company": [
{
"origin": "2013P00109",
"type": "LJ",
"naf": "5610A",
},
{
"origin": "2013P00110",
"type": "FJ",
"naf": "5481"
}
]
}
});
(...)
Server side, I try to build an array with only the "origin" field of my array "data_company":
function getCoords(params, callback) {
var arrOrigin = params.data_company.map(function(d) {
return d.origin;
});
(...)
}
And I get this error :
TypeError: Object [object Object] has no method "map"
It seems that my "data_company" is not recognized as an array but as an object. I tried to JSON.parse(params) before but I get another error :
SyntaxError: Unexpected token o
Anyway, I'm stuck. Do you have any clue to help me to solve this ?
Thanks

Related

JavaScript url in json returns 501 but string url does not

So I have the following problem:
I try to pull data from iCloud using CloudKit (HTTP requests)
The iCloud entity contains a CKAsset and I need the download URL which a POST request to https://api.apple-cloudkit.com/database/1/... returns. However, if I try to download the data from this URL, it returns a 501 error but if I print the URL to the console and paste that into the browser, the browser downloads the file.
It gets even weirder because if I implement the URL I printed to the console directly into the code everything works! I am converting the URL in the JSON response to a string so IDK what's wrong.
CloudKit response:
{ "records" : [ { "recordName" : "xxxxxxxxxxxx", "recordType" : "xxxxxxx", "fields" : { "file" : { "value" : { "fileChecksum" : "AZJ1FbmpL7caqaksfwrFm3586o5+", "size" : 303, "downloadURL" : "https://cvws.icloud-content.com/B/AZJ1Fbmpxxxaxxxxxxx/${f}?xxxxxxxx..." }, "type" : "ASSETID" },},} ] }
I shorted the response so that it only contains the relevant stuff.
I tried to get the URL with the following code: var url = data["records"][0]["fields"]["file"]["value"]["downloadURL"];
Already tried with .toString() and var url == "" + data["records"]....
It works if I do var url = "https://cvws.icloud-content.com/B/AZJ1Fbmpxxxaxxxxxxx/${f}?xxxxxxxx..." but obviously this is no real solution.
Help is really appreciated!
EDIT:
Here is the code that downloads the file from downloadURL. I'm using a library called zip.js because the file is a zip file (with a different file extension):
zip.createReader(
new zip.HttpReader(url),
function (reader) {
reader.getEntries(async function (entries) {
if (entries.length) {
entries[0].getData(
new zip.TextWriter(),
async function (text) {
reader.close(function () {
// onclose callback
});
},
function (current, total) {
// onprogress callback
}
);
} else {
}
});
},
function (error) {
// onerror callback
}
);
EDIT 2:
I found out something that might be interesting: If I paste the URL directly into the code, status code 200 returns from disk cache. I tried loading the website in incognito mode and I had to reload once to get it working. Because I receive a new download ID on every refresh, it can't cache a status code.
This works if the URL is valid
You need to look in the network tab to see what is the matter. For example the ${f} looks suspicious
const data = {
"records": [{
"recordName": "xxxxxxxxxxxx",
"recordType": "xxxxxxx",
"fields": {
"file": {
"value": {
"fileChecksum": "AZJ1FbmpL7caqaksfwrFm3586o5+",
"size": 303,
"downloadURL": "https://cvws.icloud-content.com/B/AZJ1Fbmpxxxaxxxxxxx/${f}?xxxxxxxx..."
},
"type": "ASSETID"
},
},
}]
}
location = data.records[0].fields.file.value.downloadURL;
The code that you have above does work to pull the URL out of the object (run code below). Are you sure that data holds the information in the format you're expecting and that the URL is correct?
var data = { "records" : [ { "recordName" : "xxxxxxxxxxxx", "recordType" : "xxxxxxx", "fields" : { "file" : { "value" : { "fileChecksum" : "AZJ1FbmpL7caqaksfwrFm3586o5+", "size" : 303, "downloadURL" : "https://cvws.icloud-content.com/B/AZJ1Fbmpxxxaxxxxxxx/${f}?xxxxxxxx..." }, "type" : "ASSETID" },},} ] };
// Original
var url = data["records"][0]["fields"]["file"]["value"]["downloadURL"];
// Object notation
var url2 = data.records[0].fields.file.value.downloadURL;
console.log(url);
console.log(url2);
Ok so I found a solution. This has nothing to do with the actual URL, it is fine, but rather the way how zip.js downloads data. It first makes a HEAD request and because the iCloud servers do not support these, it returns 501. The static domains worked because it somehow cached 200 OK, even though 501 returned.
Thank you to everyone for their help!

Suitescript RESTlet data get Error Empty JSON string

I have issue using POST Function, I want to transform Transfer Order to Item Receipt, But when I tried to execute the script, it failed with error "org.mozilla.javascript.EcmaError: SyntaxError: Empty JSON string (INVOCATION_WRAPPER$sys#24".
Anyone can help me about my issue ?
Here is my Suitescript Code :
function postData (receiptItem) {
doValidation([receiptItem.recordtype], ['recordtype'], 'POST');
if (receiptItem.recordtype == 'transferorder') {
var recordId = [];
var recStr = [];
var objRecord = record.transform({
fromType: record.Type.TRANSFER_ORDER,
fromId: 131, // transfer Order internalid
toType: record.Type.ITEM_RECEIPT,
defaultValues: {
customform: '433'}
});
var itemReceiptId = objRecord.save({
enableSourcing: false,
ignoreMandatoryField: false
});
recordId.push(itemReceiptId)
log.debug({
"title": "[success] recordId: ",
"details": recordId
});
var recLoad = record.load({
type: receiptItem.recordtype,
id: recordId.getValue('internalid')
});
recStr.push({
use_form: recLoad.getText('customform'),
tran_id: recLoad.getValue('tranid'),
tran_date: recLoad.getValue('trandate'),
tran_from: recLoad.getValue('transferlocation'),
tran_to: recLoad.getValue('location'),
tran_ord_id: recLoad.getvalue('createdfrom'),
tran_memo: recLoad.getValue('memo')
});
log.debug({
"title": "recStr",
"details": recStr
});
return recStr;
}
}
return {
post: postData
};
});
It's a syntax error, very likely some misplaced bracket.
Make sure you are posting valid JSON and that the content type is set on your request
You must send data as JSON. if empty or no data then send {} at least in POST as ContentType is Application/JSON. ECMA Standard. The error message clearly states that "Empty JSON string".
Then try this in Postman tool.

Expected response to contain an array but got an object

So I'm new in Angular, and I've looked over various other solutions, but no one seemed to work for me. My app needs to take some data from mongodb database and show it to the client. The thing is I get
Error: [$resource:badcfg] Error in resource configuration for action query. Expected response to contain an array but got an object
Here is my SchoolCtrl.js on the client
app.controller('SchoolsCtrl', function($scope, SchoolResource) {
$scope.schools = SchoolResource.query();
});
Here is my ngResource
app.factory('SchoolResource', function($resource) {
var SchoolResource = $resource('/api/schools/:id', {id: '#id'}, { update: {method: 'PUT', isArray: false}});
return SchoolResource;
});
This is my SchoolsController on the server
var School = require('mongoose').model('School');
module.exports.getAllSchools = function(req, res, next) {
School.find({}).exec(function(err, collection) {
if(err) {
console.log('Schools could not be loaded: ' + err);
}
res.send(collection);
})
};
I tried adding IsArray: true, tried adding [] after 'SchoolResource' in the resource, tried changing routes, nothing worked. I wanted to see what actually is returned, that the query complained is not array, so I turned it to string and this was the result:
function Resource(value) { shallowClearAndCopy(value || {}, this); }
I have no idea why it returns a function. Can anyone help me?
That error message usually means your server is returning JSON representing a single object, such as:
{"some": "object", "with": "properties"}
when Angular is expecting JSON representing an array, like:
[ {"some": "object", "with": "properties"}, {"another": "object", "with": "stuff"} ]
Even if there is only a single result, query expects JSON for an array:
[ {"a": "single", "result": "object"} ]
You can verify this by simply loading your API call into the browser and checking it out. If there aren't square brackets around the whole JSON response, it isn't an array.
It happened to me too, but then I printed the object in the console and found out that there was something like this:
{ options:{....},results:[ ...the Array I was looking for... ]}
so all you need to do there is
res.send(collection.results);
I hope this helps

Facebook Feed - JS SDK

I am trying to create a user's feed on my page using Facebook JS SDK but I am having issues accessing the values of nested objects.
This is my code:
FB.api('/me/feed', function(response) {
alert(response.data);
});
The alert here will return [object Object]
The data object is this:
{
"data": [
{
"message": "Some message",
"id": "some ID",
"created_time": "2014-01-05T22:46:10+0000"
}
],
"paging": {
"previous": "Link",
"next": "Link"
}
}
I need to access the message part of the object but I don't know how.
Simply access the properties directly
FB.api('/me/feed', function(response) {
alert(response.data.message);
});
I had to use JSON after all
FB.api('/me/feed',{limit:10}, function(response){
var jsonText = JSON.stringify(response.data,["picture"]);
alert(jsonText);
});
This will return an array with all the values of 'picture'
This is the example output
[{"picture":"https://fbcdn-photos-d-a.akamaihd.net"},
{"picture":"https://fbcdn-photos-g-a.akamaihd.net"},
{"picture":"https://fbexternal-a.akamaihd.net"},{},
{"picture":"https://fbcdn-profile-a.akamaihd.net"}]
It looks likedata is an array with a single element, so to get message, you will want to use response.data[0].message

AngularJS / Restangular routing "Cannot set property 'route' of undefined"

I have a AngularJS-based frontend using restangular to fetch records from a Django backend I've built.
I'm making a call for a client list with the following:
var app;
app = angular.module("myApp", ["restangular"]).config(function(RestangularProvider) {
RestangularProvider.setBaseUrl("http://172.16.91.149:8000/client/v1");
RestangularProvider.setResponseExtractor(function(response, operation) {
return response.objects;
});
return RestangularProvider.setRequestSuffix("/?callback=abc123");
});
angular.module("myApp").controller("MainCtrl", function($scope, Restangular) {
return $scope.client = Restangular.all("client").getList();
});
Chrome is showing the backend returning data with an HTTP 200:
abc123({
"meta": {
"limit": 20,
"next": "/client/v1/client/?callback=abc123&limit=20&offset=20",
"offset": 0,
"previous": null,
"total_count": 2
},
"objects": [{
"id": 1,
"name": "Test",
"resource_uri": "/client/v1/client/1/"
}, {
"id": 2,
"name": "Test 2",
"resource_uri": "/client/v1/client/2/"
}]
})
But once that happens I'm seeing the following stack trace appear in Chrome's console:
TypeError: Cannot set property 'route' of undefined
at restangularizeBase (http://172.16.91.149:9000/components/restangular/src/restangular.js:395:56)
at restangularizeCollection (http://172.16.91.149:9000/components/restangular/src/restangular.js:499:35)
at http://172.16.91.149:9000/components/restangular/src/restangular.js:556:44
at wrappedCallback (http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js:6846:59)
at http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js:6883:26
at Object.Scope.$eval (http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js:8057:28)
at Object.Scope.$digest (http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js:7922:25)
at Object.Scope.$apply (http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js:8143:24)
at done (http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js:9170:20)
at completeRequest (http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js:9333:7) angular.js:5754
I did a breakpoint on line 395 in in restangular.js:
L394 function restangularizeBase(parent, elem, route) {
L395 elem[config.restangularFields.route] = route;
The first time it hits the breakpoint elem is just an object and route has the value of client.
The second time the breakpoint is hit elem is undefined and route has the value of client.
Any ideas why elem would be undefined the second time around?
When requesting lists, Restangular expects the data from the server to be a simple array. However, if the resulting data is wrapped with result metadata, such as pagination info, it falls apart.
If you are using Django REST Framework, it will return results wrapped like this:
{
"count": 2,
"next": null,
"previous": null,
"results": [
{
"id": 1,
"name": "Foo"
},
{
"id": 2,
"name": "Bar"
}
]
}
To translate this, you need to create a response extractor function. It's easiest to specify in the module config:
angular.module('myApp', ['myApp.controllers', 'restangular']).
config(function(RestangularProvider) {
RestangularProvider.setBaseUrl("/api");
// This function is used to map the JSON data to something Restangular
// expects
RestangularProvider.setResponseExtractor(function(response, operation, what, url) {
if (operation === "getList") {
// Use results as the return type, and save the result metadata
// in _resultmeta
var newResponse = response.results;
newResponse._resultmeta = {
"count": response.count,
"next": response.next,
"previous": response.previous
};
return newResponse;
}
return response;
});
});
This rearranges the results to be a simple array, with an additional property of _resultmeta, containing the metadata. Restangular will do it's thing with the array, and it's objects, and you can access the _resultmeta property when handling the array as you would expect.
I'm the creator of Restangular.
The restangularizeBase function is called first for your collection and then for each of your elements.
From the StackTrace, the element is OK, but once the collection is sent to restangularizeBase, it's actually undefined. Could you please console.log response.objects? Also, please update to the latest version.
Also, for the default request parameter, you should be using defaultRequestParams instead of the requestSuffix. requestSuffix should only be used for the ending "/"
Let me know if I can help you some more!

Categories

Resources