axios GET data appearing as [undefined, undefined] in div - javascript

I'm trying to render a url's JSON data in the browser, but it's appearing in the div as undefined, undefined. When I put its response in console.log the object and its data appears, so there's some sort of disconnect between it appearing in the console and the browser. I've gotten the rest of my data (other REST calls) to appear, but until I fix this problem I won't be able to see them and continue with my project.
Any thoughts on this? I've been struggling with getting this data for a while and it's been bugging me.
PS - Not sure if it helps, but I'm using IE11 with this one (not that I want to, but I have little say in the matter).
index.js:
import axios from 'axios';
import officeComponent from './SiteAssets/scripts/office.js' // --- trying to put data here
import mattsComponent from './SiteAssets/scripts/matt.js'
import bioComponent from './SiteAssets/scripts/bio.js'
var queryDict = {};
location.search.substr(1).split("&").forEach(function(item) {
queryDict[item.split("=")[0]] = item.split("=")[1]
});
axios.all([
// Firm Directory
axios.get(__[redacted].[redacted] + "/[redacted]/Odata/Odata.ashx/HSJS20FirmDirectory?hsf=#UserName=" + queryDict.uname + "&$select=PreferredName,...otherinfo...,SPID", {
withCredentials: true,
headers: {
"Accept": "application/json; odata=verbose",
"Content-Type": "application/json"
}
}),
... // ---------- other GET requests
]).then(axios.spread((firm, bio, edu) => { // params order is important (firmData, bioData, etc. must follow that order)
let firmData = firm.data.d.results[0];
let bioData = bio.data.d.results[0];
// Office Info (relies on Firm Directory (firmData) SPID)
axios.get(__[redacted].[redacted] + "/[redacted]/Odata/Odata.ashx/OFM_Resources?$select=FloorMap,FloorMapID,ResourceLocation,Office,OfficeID,Office_Number&hsf=#ResourceType=Person%20AND%20User_Link_ID=" + firmData.spid + "&hso=OfficeID", {
withCredentials: true,
headers: {
"Accept": "application/json; odata=verbose",
"Content-Type": "application/json"
}
})
.then(function(response) {
let oComp = new officeComponent(response.data.d.results);
oComp.loadOfficeData(response.data.d.results);
console.log('oComp', response.data.d.results); // --------- shows the object tree with all of the JSON data
}).catch(function(err) {
console.log(err);
}),
// Matts Info (relies on Bio TK number)
axios.get(__[redacted].[redacted] + "/[redacted]/Odata/Odata.ashx/MattsTeams?hsf=#MattStatus=active,pending%20AND%20TkNumber=%27" + bioData.number + "%27", {
withCredentials: true,
headers: {
"Accept": "application/json; odata=verbose",
"Content-Type": "application/json"
}
}).then(function(response) {
let mComp = new mattsComponent(response.data.d.results);
mComp.loadMattsData(response.data.d.results);
}).catch(function(err) {
console.log(err);
})
let bComp = new bioComponent();
bComp.loadBioData(bioData);
bComp.loadEduData(eduData);
office.js:
import $ from 'jquery';
// ------------------- //
console.log("office.js working")
export default class {
constructor() {
}
loadOfficeData(response) {
$("#seat-val").append(response.office_number + ", " + response.floormap);
}
}
Office Data JSON:
{
"d": {
"results": [
{
"floormap": "[location here]",
"floormapid": 10,
"resourcelocation": "[redacted]",
"office": "[location here]",
"officeid": 3,
"office_number": "00-605"
}
]
}
}

Looks like results is an array, so you must access it as:
response[0].office_number
and
response[0].floormap

Related

Get data from Google Ads API using App Script

I wanna get out campaigns reports using Google Rest API and it does'nt work in Google ads Apps script.
My code:
function main() {
const API_VERSION = "12";
const CUSTOMER_ID = "***"; //contais real custommer ID
const DEVELOPER_TOKEN = "***"; //contais real developper ID
const MANAGER_CUSTOMER_ID = "***"; //contais real manager ID
const OAUTH2_ACCESS_TOKEN = ""; //contais real ACCES TOKEN
const data = {
"pageSize": 10000,
"query": "SELECT ad_group_criterion.keyword.text, ad_group_criterion.status FROM ad_group_criterion WHERE ad_group_criterion.type = 'KEYWORD' AND ad_group_criterion.status = 'ENABLED'"
};
const url = `https://googleads.googleapis.com/v${API_VERSION}/customers/${CUSTOMER_ID}/googleAds:search`;
const options = {
method: "POST",
headers: {
"Content-Type": "application/json",
"developer-token": DEVELOPER_TOKEN,
"login-customer-id": MANAGER_CUSTOMER_ID,
"Authorization": `Bearer ${OAUTH2_ACCESS_TOKEN}`
},
body: JSON.stringify(data),
"muteHttpExceptions": true
};
Logger.log(UrlFetchApp.fetch(url, options));
}
Result error:
{
"error": {
"code": 400,
"message": "Request contains an invalid argument.",
"status": "INVALID_ARGUMENT",
"details": [
{
"#type": "type.googleapis.com/google.ads.googleads.v12.errors.GoogleAdsFailure",
"errors": [
{
"errorCode": {
"queryError": "UNEXPECTED_END_OF_QUERY"
},
"message": "Error in query: unexpected end of query."
}
],
"requestId": "zKBR9-dJoG9NWAx3iJea2g"
}
]
}
}
But query is valid https://developers.google.com/google-ads/api/fields/v11/query_validator
enter image description here
Could you plese help?
Thanks
I wanna get out campaigns reports using Google Rest API and it does'nt work. My code and result is above.
Based on the documentation of UrlFetchApp, 'body' is not the correct option for passing in the query. You want 'payload'.
const options = {
method: "POST",
headers: {
"Content-Type": "application/json",
"developer-token": DEVELOPER_TOKEN,
"login-customer-id": MANAGER_CUSTOMER_ID,
"Authorization": `Bearer ${OAUTH2_ACCESS_TOKEN}`
},
payload: JSON.stringify(data),
"muteHttpExceptions": true
};

Trying to create multisig account for NEM on local machine but getting error

Hello Everyone I am trying to make plugin from Buildfire to be bale to create NEM account and to change it into multisig account using local network (ei localhost)
Here are the code snippets for the required things I would like to ask weather there is an issue in making of JSON missing bits in the json or any other errors I need to look up, I have tried to look up error and it's solution but met with no results. The error I get is :
"error: "Internal Server Error" message: "expected value for property
transaction, but none was found" status: 500"
let done = $.ajax({
url: "http://127.0.0.1:7890/account/generate"
}).done(function (data) {
/// check you have data to report on
///if (data && data.list && data.list.length) {
/// fill in the UI with the new data
var report = data;
PubKey = report.publicKey;
PKey = report.privateKey;
$('#address').text("Created Account");
$('#balance').text(report.address);
$('#summary').text(report.privateKey);
$('#vested').text(report.publicKey)
///}
});
var date = new Date();
var TS = date.getTime();
var xyz = {
xyz: JSON.stringify({
"transaction":
{
"timeStamp": TS, ///needs to be changed to current timestamp from creating of account
"fee": 20, ///have to check
"type": 4097,
"deadline": TS + 30000, ///need to be changed
"version": -1744830462, /// main(real) network 1744830465,
"signer": PubKey,
"modifications": [
{
"modificationType": 1,
"cosignatoryAccount": PbKey
}
],
"minCosignatories" : {
"relativeChange": 1
}
},
"privateKey": PKey
})
};
fetch("http://127.0.0.1:7890/transaction/prepare-announce",{
method : 'POST',
headers : {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json'
},
body : JSON.stringify(xyz)
}).then(function (response) {
return response.json();
})
.then(function (result) {
alert(result);
}).catch (function (error) {
console.log('Request failed', error);
});
did you try normal transaction?
It looks you don't sign your transaction.
and DON'T FETCH YOUR PRIVATE KEY ON NETWORK.

Fetch(): Request body malformed

I want to make a fetch request to an API that accepts different types of body requests: twitter handle, facebook link, phone number, etc. The structure of the body is:
body: {
"typeOfHandle": "input"
}
Since there are different types of handles, I test the input type and assign it to the body accordingly, as seen below:
// handle is the input
let atSign = /^[#]/,
handleIsTwitter = atSign.test(handle.value),
handleType;
handleIsTwitter ? handleType = `"` + "twitter" + `"` : console.log("not twitter");
let abc = `"` + handle.value + `"`;
let bodyOfFetch = `{${handleType}: ${abc}}`;
console.log("body: " + bodyOfFetch);
fetch("xxx", {
method: "POST",
headers: {
Authorization: "xxx"
},
body: JSON.stringify(bodyOfFetch)
})
.then(function(res) {
return res.json();
})
.then(function(json) {
console.log(json);
});
However, this method returns a body malformed error. When I do the request statically (i.e. replace the variables with static text, e.g. "twitter": "#alex") it works. I double-triple-quadruple checked the syntax, I don't think that is the problem. Can it be an issue on the API's side?
In your example bodyOfFetch is a string ({"twitter": "#alex"}). Either you can send it directly, this is:
fetch("xxx", {
method: "POST",
headers: {
Authorization: "xxx"
},
body: bodyOfFetch
})
Or you can send a stringify object:
fetch("xxx", {
method: "POST",
headers: {
Authorization: "xxx"
},
body: JSON.stringify({[handleType]: abc})
})
But sending JSON.stringify(bodyOfFetch) will stringify a json string, this will add surrounding " and escape existing quotation marks: "{\\"twitter\\": \\"#alex\\"}"
Hope this helps.

Graphql query with $http.post does not work

The request for the code below goes all ok but I don't get any data back (Just says "Error Not Found" in the "preview" tab of the request in chrome). I try the same query in GraphiQL and it gives back relevant data. I am not sure what I am missing here. Please advise, kind of stuck with this.
PlayService.prototype.getPlays = function(playID) {
//The query.
const playsQuery = `query ($playid: String) {
plays(id: $playid) {
id
items {
nodes {
id
name
}
}
}
}`;
// variables to pass.
const variables = {
playid: playID
};
//The request.
const result = $http.post(
/graphql,
{
method: 'POST',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ playsQuery, variables })
}
);
return result && result.data;
};
You appear to be sending the data body as:
{
playsQuery: "<query string>",
variables: {}
}
The GraphQL spec specifies that you must follow this format for GraphQL queries over REST:
http://graphql.org/learn/serving-over-http/
{
"query": "...",
"operationName": "...",
"variables": { "myVariable": "someValue", ... }
}

github says cannot parse json while creating a repo in rest api

I'm learning REST api for github and trying to create a new repository by running a JS. Here is my function for creating a new repo: the token is generated, and all access/scopes is granted for my token.
function createNewRepo(userId, name){
var options = {
url: urlRoot + "/user/repos",
method: 'POST',
headers: {
"User-Agent": "EnableIssues",
"content-type": "application/json",
"Authorization": token,
"name": name,
"description": "This is repo creating by REST",
"homepage": "https://github.com",
"private": false,
"has_issues": true,
"has_projects": true,
"has_wiki": true,
}
};
//console.log(eval(options));
request(options, function (error, response, body)
{
var obj = JSON.parse(body);
console.log( obj );
});
}
however when running this, I find,
{ message: 'Problems parsing JSON', documentation_url: 'https://developer.github.com/v3' }
I'm not sure how exactly could the JSON be invalid.
Also, the documentation says it must include public_repo or repo which I'm also not sure how to apply here.
This for me has created the repository.
var myToken = "token INSERTHERETHETOKEN"; // <-- there must be the word token before the actual token.
var urlRoot = "https://api.github.com";
var request = require("request");
function createNewRepo(user, name, token){
var options = {
url: urlRoot + "/user/repos",
method: 'POST',
headers: {
"User-Agent": user,
// "content-type": "application/json", This is set by json:true
"Authorization": token,
"Accept": "application/vnd.github.v3+json"
},
body: {
"name": name,
"description": "This is repo creating by REST",
"homepage": "https://github.com",
"private": false,
"has_issues": true,
"has_projects": true,
"has_wiki": true
},
json: true
};
request(options, function (error, response, body) {
// Do your stuff... but notice that response
// is already a json object and you don't need to parse it.
});
}
createNewRepo("YourGithubUser", "test.repository", myToken);

Categories

Resources