Uncaught TypeError: datapoints.data.map is not a function at XMLHttpRequest.xmlhttp.onreadystatechange - xmlhttprequest

Can anyone help me? I'm really bad at programming
Error :Uncaught TypeError: datapoints.data.map is not a function at XMLHttpRequest.xmlhttp.onreadystatechange
const xmlhttp = new XMLHttpRequest();
const url = '//url//';
xmlhttp.open('GET', url, true);
xmlhttp.send();
xmlhttp.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200){
const datapoints = JSON.parse(this.responseText);
//console.log(datapoints);
const labelsboy = datapoints.data.map(function(item){
return item.boy;
});
console.log(labelsboy);
}
}
file JSON API
{
"status": true,
"row": 2,
"data": {
"boy": 10,
"girl": 15
}
}

map is an array function but datapoints.data is an object. It seems like you are just trying to get one value from the object so you can just access it directly.
const labelsboy = datapoints.data.boy;
console.log(labelsboy);

Related

Getting "spc message cannot be null" as response

Getting "spc message cannot be null" as response every time while providing implementation of Shaka player to play fairplay content on safari browser.Tried many ways to provide spc message in body and header also and we are actually sending it that i can see in network tab nut still cant find a solution. Here is the code below.
if (this.platform.getBrowserPlatform() === Constants.PLATFORMS.SAFARI_WEB) {
this.shakaPlayer.configure({
drm: {
servers: {
'com.apple.fps.1_0': `${this.config.baseUrl}${Constants.DRM_FAIRPLAY_LICENSE}`,
},
advanced: {
'com.apple.fps.1_0': {
serverCertificate: cert,
},
},
},
});
let that = this //,licenseUri;
this.shakaPlayer.configure('drm.initDataTransform', (initData) => {
const skdUri = shaka.util.StringUtils.fromBytesAutoDetect(initData);
var contentId = skdUri.substring(skdUri.indexOf('skd://') + 6);
// licenseUri = skdUri.replace('skd://', 'https://');
const url = new URL(contentId);
const urlParams = new URLSearchParams(url.search);
const cert = that.shakaPlayer.drmInfo().serverCertificate;
let id = urlParams.get('contentId');
that.id = id;
return shaka.util.FairPlayUtils.initDataTransform(initData, id, cert);
// let skdUrl = shaka.util.StringUtils.fromBytesAutoDetect(initData);
// licenseUri = skdUrl.replace('skd://', 'https://');
// const cert = that.shakaPlayer.drmInfo().serverCertificate;
// return shaka.util.FairPlayUtils.initDataTransform(initData, licenseUri, cert);
});
this.shakaPlayer.getNetworkingEngine().registerRequestFilter((type, request) => {
if (type != shaka.net.NetworkingEngine.RequestType.LICENSE) {
return;
}
let token = localStorage.getItem('auth');
let testToken = JSON.parse(token);
const originalPayload = new Uint8Array(request.body);
const base64Payload = shaka.util.Uint8ArrayUtils.toBase64(originalPayload);
const params = `{ "spc": "${base64Payload}", "assetId":"${that.id}"}`;
request.body = shaka.util.StringUtils.toUTF8(params);
request.headers['Content-Type'] = 'application/json';
request.headers['Authorization'] = `JWT ${testToken.access_token}`
console.log("request.body", request.body)
});
this.shakaPlayer.getNetworkingEngine().registerResponseFilter((type, response) => {
if (type != shaka.net.NetworkingEngine.RequestType.LICENSE) {
return;
}
console.log("license passed")
let responseText = shaka.util.StringUtils.fromUTF8(response.data);
responseText = responseText.trim();
if (responseText.substr(0, 5) === '<ckc>' &&
responseText.substr(-6) === '</ckc>') {
responseText = responseText.slice(5, -6);
}
response.data = shaka.util.Uint8ArrayUtils.fromBase64(responseText).buffer;
});
this.shakaPlayer.load(this.getProgramUrl(channel, program, restart)).then(() => {
console.log('1', this.shakaPlayer.isTextTrackVisible());
console.log('2', this.shakaPlayer.getTextTracks());
console.log('3', this.shakaPlayer.getTextLanguages());
}).catch((error) => {
console.log(error);
});
Smooth play of fairplay content on safari or some advise what can i do in this case

Cloudflare ESI worker / TypeError: Body has already been used

I'm trying to use a CloudFlare worker to manage my backend ESI fragments but i get an error:
Uncaught (in promise) TypeError: Body has already been used. It can only be used once. Use tee() first if you need to read it twice.
Uncaught (in response) TypeError: Body has already been used. It can only be used once. Use tee() first if you need to read it twice.
I don't find where the body has already been used
The process is:
get a response with the parts
Transform the body by replacing parts fragments with sub Backend calls (streamTransformBody function)
return the response
addEventListener("fetch", event => {
event.respondWith(handleRequest(event.request))
});
const esiHeaders = {
"user-agent": "cloudflare"
}
async function handleRequest(request) {
// get cookies from the request
if(cookie = request.headers.get("Cookie")) {
esiHeaders["Cookie"] = cookie
console.log(cookie)
}
// Clone the request so that it's no longer immutable
newRequest = new Request(request)
// remove cookie from request
newRequest.headers.delete('Cookie')
// Add header to get <esi>
newRequest.headers.set("Surrogate-Capability", "abc=ESI/1.0")
console.log(newRequest.url);
const response = await fetch(newRequest);
let contentType = response.headers.get('content-type')
if (!contentType || !contentType.startsWith("text/")) {
return response
}
// Clone the response so that it's no longer immutable
const newResponse = new Response(response.body, response);
let { readable, writable } = new TransformStream()
streamTransformBody(newResponse.body, writable)
newResponse.headers.append('x-workers-hello', 'Hello from
Cloudflare Workers');
return newResponse;
}
async function streamTransformBody(readable, writable) {
const startTag = "<".charCodeAt(0);
const endTag = ">".charCodeAt(0);
let reader = readable.getReader();
let writer = writable.getWriter();
let templateChunks = null;
while (true) {
let { done, value } = await reader.read();
if (done) break;
while (value.byteLength > 0) {
if (templateChunks) {
let end = value.indexOf(endTag);
if (end === -1) {
templateChunks.push(value);
break;
} else {
templateChunks.push(value.subarray(0, end));
await writer.write(await translate(templateChunks));
templateChunks = null;
value = value.subarray(end + 1);
}
}
let start = value.indexOf(startTag);
if (start === -1) {
await writer.write(value);
break;
} else {
await writer.write(value.subarray(0, start));
value = value.subarray(start + 1);
templateChunks = [];
}
}
}
await writer.close();
}
async function translate(chunks) {
const decoder = new TextDecoder();
let templateKey = chunks.reduce(
(accumulator, chunk) =>
accumulator + decoder.decode(chunk, { stream: true }),
""
);
templateKey += decoder.decode();
return handleTemplate(new TextEncoder(), templateKey);
}
async function handleTemplate(encoder, templateKey) {
const linkRegex = /(esi:include.*src="(.*?)".*\/)/gm
let result = linkRegex.exec(templateKey);
let esi
if (!result) {
return encoder.encode(`<${templateKey}>`);
}
if (result[2]) {
esi = await subRequests(result[2]);
}
return encoder.encode(
`${esi}`
);
}
async function subRequests(target){
target = esiHost + target
const init = {
method: 'GET',
headers: esiHeaders
}
let response = await fetch(target, init)
if (!response.ok) {
return ''
}
let text = await response.text()
return '<!--esi-->' + text + '<!--/esi-->'
}

Web Application ArcGIS JS API error adding layer

I'm developing a custom widget for WebApp Builder. The widget calls a Geoprocessing service and the result must be added to map, but when I call a function this.map.addLayer() I receive the error message:
TypeError: this.map.addLayer is not a function
at Widget.js?wab_dv=2.6:839
at Object._successHandler (init.js:2238)
at Object._getResultDataHandler (Geoprocessor.js:11)
at init.js:63
at Object.load (Geoprocessor.js:12)
at init.js:1042
at c (init.js:103)
at d (init.js:103)
at b.Deferred.resolve.callback (init.js:105)
at c (init.js:104) "TypeError: this.map.addLayer is not a function
This is the snippet of my code:
submitGpLr: function (tab1) {
let params = {
json: tab1
};
// lancia il geoprocessing, i callback sono sotto
this.gpLr.submitJob(params, lang.hitch(this, this.gpLrJobComplete), this.gpLrJobStatus, this.gpLrJobFailed);
},
gpLrJobComplete: function (jobinfo) {
this.gpLr.getResultData(jobinfo.jobId, "Output_Layer", function (results) {
console.log(results);
let jsonResult = results.value;
// function addResultToMap
let SR = jsonResult.spatialReference;
let GT = "esriGeometryPolyline";
let layerDefinition = {
"geometryType": GT,
"spatialReference": SR,
"fields": jsonResult.fields
};
let featureCollection = {
layerDefinition: layerDefinition,
featureSet: {
"geometryType": GT,
"spatialReference": SR,
"features": jsonResult.features
}
};
let resultLayer = new FeatureLayer(featureCollection, {
showLabels: true,
spatialReference: SR
});
let sls = new esri.symbol.SimpleLineSymbol(
esri.symbol.SimpleLineSymbol.STYLE_SOLID,
new esri.Color([255, 0, 0]), 3.5
);
this.map.addLayer(resultLayer);
});
},
gpLrJobFailed: function (err) {
console.log("error");
console.log(err);
},
gpLrJobStatus: function () {
}
This is my setEventHandler:
this.own(on(this.gpLr_Submit, "click", () => {
let id = this.selectedMainTabId;
let tabNewStr = JSON.stringify(this.grids[id + '_IN']['_originalData']);
this.submitGpLr(tabNewStr);
}));
How can I fix this error? I don't try the error in my code.
I think, "this" reference to "Window" object. Your this should reference to, your widget class.You should set instance like this when, onstartup event in widget.Then you can use instance.map like this:
startup: function () {
console.log('YourCustomWidget::startup');
YourCustomWidget.SetInstance(this);
}
//Singleton design
YourCustomWidget.Instance = undefined;
YourCustomWidget.GetInstance = function () {
return this.Instance;
}
YourCustomWidget.SetInstance = function (instance) {
AkkrFiltrelemeVeRaporlama.Instance = instance;
}
...
...
...
...
gpLrJobComplete: function (jobinfo) {
var instance = YourCustomWidget.Instance;
//
//
//
instance .map.addLayer(resultLayer);
}

How to count the number of elements in this particular object

I am making a call to an API and the response is somehow what I expect. However, I want to count the number of elements returned and I can not do it. This is what I think is important from the code.
Call in Vue component
data(){
return {
messages: {}
}
},
loadMessages(){
axios.get("api/messagesmenu")
.then((data) => { this.messages = data.data})
}
Api controller
public function index(){
$messages = Message::all()->where('read_at', NULL);
if(isset($messages)){
foreach($messages as $message){
$from = User::find($message->from_id);
$message->fromPrenom = $from->first_name;
$message->fromNom = $from->last_name;
$message->fromImage = $from->user_image;
}
}else{
$messages = [];
}
return $messages;
}
Type of response from the API
{"3":{"id":560,"from_id":2,"to_id":1,"content":"tgr","created_at":"2019-07-15 16:59:03","read_at":null,"fromPrenom":"abdel1","fromNom":"Hidalgo","fromImage":"user2-160x160.png"}}
I want to count the number of objects I obtain. if (in vue component) I do
this.messages.length
it returns undefined
Try this:
const messages = {"3":{"id":560,"from_id":2,"to_id":1,"content":"tgr","created_at":"2019-07-15 16:59:03","read_at":null,"fromPrenom":"abdel1","fromNom":"Hidalgo","fromImage":"user2-160x160.png"}}
console.log(Object.keys(messages).length) // 1
Or in your code:
...
.then((data) => {
this.messages = data.data
console.log(Object.keys(this.messages).length)
})

IBM Worklight 6.0 - Getting "Uncaught type error cannot call method 'initCollection' of undefined"

I'm working with Worklight to build an application which uses a local storage. I declared a function createCollection() in common/js/myApp.js.
However when I run it on the browser simulator, the console JavaScript shows:
Uncaught TypeError: Cannot call method 'initCollection' of undefined.
Any suggestions?
My JavaScript:
function wlCommonInit(){
// Common initialization code goes here
}
// inizializzazione json
window.onload = createCollection;
var isOpen = true;
var menuboxw = $("#menubox").css("width");
$("#contentbox").css("left",menuboxw);
var headerh = $("#header").height();
$("#contentbox").css("top", headerh);
$("#menu_btn").click(function(){menu()});
// apertura/chiusura menu principale
function menu() {
if(isOpen){
$('#contentbox').animate({ left: -5 }, 1);
$("#menubox").css("visibility", "hidden");
isOpen = false;
}
else{
$('#contentbox').animate({ left: menuboxw }, 1);
$("#menubox").css("visibility", "visible");
isOpen = true;
}
}
// creazione collection 'canti' e 'categorie'
function createCollection(){
WL.Logger.debug("Called createCollection");
WL.SimpleDialog.show("Message", "createCollection called", [{text: "Ok"}]);
var collectionCanti = "canti";
var searchFieldsCanti = {titolo: "string", autore: "string", id_categoria: "string", testo: "string"};
var collectionCategorie = "categorie";
var searchFieldsCategorie = {titolo: "string", attiva: "number"};
var success = function(data){
logMessage("Collection created successfully " + data);
};
var failure = function(data){
logMessage("Collection doesn't created " + data);
};
var options = {onSuccess: success, onFailure: failure};
canti = WL.JSONStore.initCollection(collectionCanti, searchFieldsCanti, options);
categorie = WL.JSONStore.initCollection(collectionCategorie, searchFieldsCategorie, options);
}
Do the following:
Remove window.onload = createCollection;
Add createCollection(); inside wlCommonInit()
BTW, that logMessage produces errors. Should probably be changed to WL.Logger.debug (which you are already utilizing in the code...).
Please go over the IBM Worklight Getting Started training material. No skipping.