Invalid Json Response when accessing third-party service with Wix Corvid - json

I am attempting to gather details about real estate properties through an external API. I've gone over their documentation relentlessly but can not figure out why I am receiving the following error:
invalid json response body at https://api.gateway.attomdata.com/propertyapi/v1.0.0/property/expandedprofile?address1=34%20Karen%20Court&address2=Bridgeport20%CT reason: Unexpected token < in JSON at position
For reference, I am posting my code. If anyone can provide any input or guidance I would greatly appreciate it!
Backend Code:
import { fetch } from 'wix-fetch';
import { wixData } from 'wix-data';
export function getDetails(address, citystatezip) {
const url = 'https://api.gateway.attomdata.com/propertyapi/v1.0.0/property/expandedprofile?address1=' + address + "&address2=" + citystatezip;
let headers = {
"apikey": "xxxxxxxx",
"accept": "application/json"
};
let options = {
headers: headers
}
console.log("Url: " + url);
return fetch(url, { method: 'get' })
.then(response => {
return response.json();
})
.then((data) => {
console.log(data);
return data;
});
}
Page Code:
wixWindow.getCurrentGeolocation()
.then((obj) => {
let timestamp = obj.timestamp; // 1495027186984
let latitude = obj.coords.latitude; // 32.0971036
let longitude = obj.coords.longitude; // 34.774391099999995
let altitude = obj.coords.altitude; // null
let accuracy = obj.coords.accuracy; // 29
let altAccuracy = obj.coords.altitudeAccuracy; // null
let heading = obj.coords.heading; // null
let speed = obj.coords.speed;
console.log(obj)
reverse(latitude, longitude)
.then(geocode => {
console.log(geocode)
let id = geocode.results[0].place_id;
details(id)
.then(detailed => {
console.log(detailed)
$w("#input12").value = geocode.results[0].address_components[0].long_name + " " + geocode.results[0].address_components[1].long_name;
$w("#input10").value = geocode.results[0].address_components[3].long_name;
$w("#input11").value = geocode.results[0].address_components[5].long_name;
$w("#text37").text = geocode.results[0].formatted_address;
$w("#googleMaps2").location = {
"latitude": latitude,
"longitude": longitude,
"description": geocode.results[0].formatted_address
};
let address = geocode.results[0].address_components[0].long_name + " " + geocode.results[0].address_components[1].long_name;
let city = geocode.results[0].address_components[3].long_name;
let state = geocode.results[0].address_components[5].short_name;
let citystate = city +"%2C" + "%20" + state;
console.log(citystate)
const uri = address;
const encoded = encodeURI(uri);
console.log(encoded);
getDetails(encoded, citystate)
.then(got => {
console.log(got)
})
});
});
Thank you in advance for any input or guidance you can offer. I have spent hours trying to figure this out to no avail.
Stay safe and stay well 😊

Related

How to make html_url into hyperlinks from fetch/json

I am learning javascript and Json so please bear with me.
I have fetched certain json data and made it visible on my webpage. All this through my GitHub api. I have three repositories in total and each contain the name of the repository a description and a html_url. I would like to make the three html_url active. So the user can click directly on them and go to that repository. I've been trying and googling but have yet to have any success. Any tips would be hugely appreciated.
Below is my js code.
`
function load () {
element = document.getElementById("gitRepos");
element.classList.toggle("hide");
const loadingStatus = document.querySelector('#gitRepos')
let url = "https://api.github.com/users/PaulEvans78/repos"
async function getrepo() {
let response = await fetch(url);
const repoList = document.getElementById("gitRepos")
const links = document.getElementById("gitRepos")
if(response.ok) {
let data = await response.json();
loadingStatus.innerText = " "
console.log(data);
for (const item of data){
createRepoLi(repoList, item.name, item.html_url, item.description)
}
} else {
console.log("HTTP-Error: " + response.status);
}
}
function createRepoLi(repoList, name, html_url, description){
const li = document.createElement('li')
li.innerText = name + "\n " + html_url + "\n " + description
li.classList.add("gitHubStyle");
repoList.appendChild(li)
}
getrepo();
}
`

Autodesk.DesignAutomation returning Unexpected token S in JSON at position 0 when calling the workitem api

I am facing a new issue with a fetch
handleSendToForge(e) {
e.preventDefault();
let formData = new FormData();
formData.append('data', JSON.stringify({
Width: this.state.Width,
Length: this.state.Length,
Depth: this.state.Depth,
Thickness: this.state.Thickness,
BottomThickness: this.state.BottomThickness,
rebarSpacing: this.state.rebarSpacing,
outputrvt: this.state.outputrvt,
bucketId: this.state.bucketId,
activityId: 'RVTDrainageWebappActivity',
objectId: 'template.rvt'
}));
this.setState({
form: formData
})
fetch('designautomation', {
method: 'POST',
body: formData,
//headers: {
// //'Content-Type': 'application/json'
// 'Content-Type': 'application/x-www-form-urlencoded',
//},
})
.then(response => response.json())
.then(data => { console.log(data) })
.catch(error => console.log(error));
}
and the code for the controller is pretty standard and is slightly modified from one of the forge examples
[HttpPost]
[Route("designautomation")]
public async Task<IActionResult> Test([FromForm] StartWorkitemInput input)
{
JObject workItemData = JObject.Parse(input.data);
double Width = workItemData["Width"].Value<double>();
double Length = workItemData["Length"].Value<double>();
double Depth = workItemData["Depth"].Value<double>();
double Thickness = workItemData["Thickness"].Value<double>();
double BottomThickness = workItemData["BottomThickness"].Value<double>();
double rebarSpacing = workItemData["rebarSpacing"].Value<double>();
string outputrvt = workItemData["outputrvt"].Value<string>();
string activityId = workItemData["activityId"].Value<string>();
string bucketId = workItemData["bucketId"].Value<string>();
string objectId = workItemData["objectId"].Value<string>();
// basic input validation
string activityName = string.Format("{0}.{1}", NickName, activityId);
string bucketKey = bucketId;
string inputFileNameOSS = objectId;
// OAuth token
dynamic oauth = await OAuthController.GetInternalAsync();
// prepare workitem arguments
// 1. input file
dynamic inputJson = new JObject();
inputJson.Width = Width;
inputJson.Length = Length;
inputJson.Depth = Depth;
inputJson.Thickness = Thickness;
inputJson.BottomThickness = BottomThickness;
inputJson.rebarSpacing = rebarSpacing;
inputJson.outputrvt = outputrvt;
XrefTreeArgument inputFileArgument = new XrefTreeArgument()
{
Url = string.Format("https://developer.api.autodesk.com/oss/v2/buckets/aecom-bucket-demo-library/objects/{0}", objectId),
Headers = new Dictionary<string, string>()
{
{ "Authorization", "Bearer " + oauth.access_token }
}
};
// 2. input json
XrefTreeArgument inputJsonArgument = new XrefTreeArgument()
{
Headers = new Dictionary<string, string>()
{
{"Authorization", "Bearer " + oauth.access_token }
},
Url = "data:application/json, " + ((JObject)inputJson).ToString(Formatting.None).Replace("\"", "'")
};
// 3. output file
string outputFileNameOSS = outputrvt;
XrefTreeArgument outputFileArgument = new XrefTreeArgument()
{
Url = string.Format("https://developer.api.autodesk.com/oss/v2/buckets/{0}/objects/{1}", bucketKey, outputFileNameOSS),
Verb = Verb.Put,
Headers = new Dictionary<string, string>()
{
{"Authorization", "Bearer " + oauth.access_token }
}
};
// prepare & submit workitem
// the callback contains the connectionId (used to identify the client) and the outputFileName of this workitem
//string callbackUrl = string.Format("{0}/api/forge/callback/designautomation?id={1}&bucketKey={2}&outputFileName={3}", OAuthController.FORGE_WEBHOOK_URL, browerConnectionId, bucketKey, outputFileNameOSS);
WorkItem workItemSpec = new WorkItem()
{
ActivityId = activityName,
Arguments = new Dictionary<string, IArgument>()
{
{ "rvtFile", inputFileArgument },
{ "jsonFile", inputJsonArgument },
{ "result", outputFileArgument }
///{ "onComplete", new XrefTreeArgument { Verb = Verb.Post, Url = callbackUrl } }
}
};
DesignAutomationClient client = new DesignAutomationClient();
client.Service.Client.BaseAddress = new Uri(#"http://localhost:3000");
WorkItemStatus workItemStatus = await client.CreateWorkItemAsync(workItemSpec);
return Ok();
}
Any idea why is giving me this error? I have tested the api using postman and it works fine but when I try to call that from a button I keep receive this error. Starting the debug it seems that the url is written correctly. Maybe it is a very simple thing that i am missing.
Cheers!
OK solved...
I was missing to add the service in the Startup and also the Forge connection information (clientid, clientsecret) in the appsettings.json
Now I need to test the AWS deployment and I guess I am done!

Why isn't my function returning the proper JSON data and how can I access it?

I'm running services to retrieve data from an API. Here is one of the services:
robotSummary(core_id, channel_name){
const params = new HttpParams()
var new_headers = {
'access-token': ' '
};
this.access_token = sessionStorage.getItem('access-token');
new_headers['access-token'] = this.access_token;
const myObject: any = {core_id : core_id, channel_name: channel_name};
const httpParams: HttpParamsOptions = { fromObject: myObject } as HttpParamsOptions;
const options = { params: new HttpParams(httpParams), headers: new_headers };
return this.http.get(this.baseURL + 'web_app/robot_summary/',options)
.subscribe(
res => console.log(res),
)
}
}
The data shows up properly on the console, but I still can't access the individual keys:
Here is how I call it:
ngOnInit(): void{
this.login.getData(this.username, this.password).subscribe((data) => {
this.robotSummaryData = this.getRobotSummary.robotSummary(this.core_id, this.channel_name);
console.log("robosummary"+ this.robotSummaryData)
});
}
When I call this function and assign it to a variable, it shows up on console as [object Object]. When I tried to use JSON.parse, it throws the error: type subscription is not assignable to parameter string. How can I access the data? I want to take the JSON object and save it as an Object with appropriate attributes. Thanks!
Do not subscribe inside your service, do subscribe in your component, change your service as follows,
robotSummary(core_id, channel_name){
const params = new HttpParams()
var new_headers = {
'access-token': ' '
};
this.access_token = sessionStorage.getItem('access-token');
new_headers['access-token'] = this.access_token; const myObject: any = { core_id: core_id, channel_name: channel_name };
const httpParams: HttpParamsOptions = { fromObject: myObject } as HttpParamsOptions;
const options = { params: new HttpParams(httpParams), headers: new_headers };
return this.http.get(this.baseURL + 'web_app/robot_summary/', options)
.map((response: Response) => response);
}
and then in your component,
ngOnInit(){
this.api..getRobotSummary.robotSummary(this.core_id, this.channel_name).subscribe((data) => {
this.data = data;
console.log(this.data);
});
}

Angular 5+ consume data from asp.net core web api

I have a problem consuming data from an ASP.NET Core 2.0 Web API with Angular 5+.
Here the steps i have done:
I have built an ASP.NET Core 2.0 WebAPI and deployed it on a server. I can consume data from postman or swagger without any problems.
Then i have created with NSwagStudio the client TypeScript service classes for my angular frontend app.
Now the problem:
I can make a request to the wep api from the frontend app and i am also recieveing the correct data in JSON-Format.
But while the mapping process to the poco object in the generated client service class, something doesnt work. I always get an object with empty attributes.
Here my code:
product.service.ts
export class ProductService {
private http: { fetch(url: RequestInfo, init?: RequestInit): Promise<Response> };
private baseUrl: string;
protected jsonParseReviver: (key: string, value: any) => any = undefined;
constructor() {
this.http = <any>window;
this.baseUrl = "http://testweb01/FurnitureContractWebAPI";
}
getByProductId(productId: string): Promise<Product[]> {
let url_ = this.baseUrl + "/api/Product/GetById?";
if (productId === undefined)
throw new Error("The parameter 'productId' must be defined.");
else
url_ += "productId=" + encodeURIComponent("" + productId) + "&";
url_ = url_.replace(/[?&]$/, "");
let options_ = <RequestInit>{
method: "GET",
headers: {
"Content-Type": "application/json",
"Accept": "application/json"
}
};
return this.http.fetch(url_, options_).then((_response: Response) => {
return this.processGetByProductId(_response);
});
}
protected processGetByProductId(response: Response): Promise<Product[]> {
const status = response.status;
let _headers: any = {}; if (response.headers && response.headers.forEach) { response.headers.forEach((v: any, k: any) => _headers[k] = v); };
if (status === 200) {
return response.text().then((_responseText) => {
let result200: any = null;
let resultData200 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver);
if (resultData200 && resultData200.constructor === Array) {
result200 = [];
for (let item of resultData200) {
var x = Product.fromJS(item);
//console.log(x);
result200.push(Product.fromJS(item));
}
}
//console.log(result200);
return result200;
});
} else if (status !== 200 && status !== 204) {
return response.text().then((_responseText) => {
return throwException("An unexpected server error occurred.", status, _responseText, _headers);
});
}
return Promise.resolve<Product[]>(<any>null);
}
And here the methods from the Product-class:
init(data?: any) {
console.log(data);
if (data) {
this.productId = data["ProductId"];
this.productNameDe = data["ProductNameDe"];
this.productNameFr = data["ProductNameFr"];
this.productNameIt = data["ProductNameIt"];
this.supplierProductId = data["SupplierProductId"];
this.supplierProductVarId = data["SupplierProductVarId"];
this.supplierProductVarName = data["SupplierProductVarName"];
this.supplierId = data["SupplierId"];
this.supplierName = data["SupplierName"];
this.additionalText = data["AdditionalText"];
this.installationCost = data["InstallationCost"];
this.deliveryCost = data["DeliveryCost"];
this.sectionId = data["SectionId"];
this.categorieId = data["CategorieId"];
this.price = data["Price"];
this.ean = data["Ean"];
this.brand = data["Brand"];
this.modifiedDate = data["ModifiedDate"] ? new Date(data["ModifiedDate"].toString()) : <any>undefined;
this.categorie = data["Categorie"] ? ProductCategory.fromJS(data["Categorie"]) : <any>undefined;
this.section = data["Section"] ? ProductSection.fromJS(data["Section"]) : <any>undefined;
}
}
static fromJS(data: any): Product {
data = typeof data === 'object' ? data : {};
let result = new Product();
result.init(data);
return result;
}
In the init() method when i look at data, it contains all the values i need. But when i for example use data["ProductId"] the value is null/undefined.
Can anyone please help?
Thanks
Here is a screenshot of my console output of the data object:
enter image description here
Now I could figure out, that i can cast the data object directly to Product:
init(data?: any) {
var p = <Product>data;
This works, but i am asking myself, why does the generated class have an init-method with manually setting of the attributes, when it is possible to cast the object directly?
NSwag is misconfigured, use DefaultPropertyNameHandling: CamelCase for ASP.NET Core
Or use the new asp.net core api explorer based swagger generator which automatically detects the contract resolver. (Experimental)

GraphQL/GraphCool Why do coordinates don't work with FLOAT?

I'm currently working on GraphQL/GraphCool wrapping a RestAPI, but when I write my resolver with Float in order to extract latitude and longitude as floats I get the following error:
"code": 5004,
"message": "Returned JSON Object does not match the GraphQL type. The field 'latitud' should be of type Float \n\n Json:
{\n \"id\": \"6115\",\n \"nombre\": \"ABARROTES LA SOLEDAD\",\n \"latitud\": \"21.85779823\",\n \"longitud\": \"-102.28161261\"\n}\n\n"
if I use String there is no problem!
RESOLVER SDL
type AbarrotesPayload {
id: ID!
nombre: String!
latitud: Float!
longitud: Float!
}
extend type Query {
feed(distancia: Int!): [AbarrotesPayload!]!
}
RESOLVER FUNCTION
"use strict";
const fetch = require("node-fetch");
const API_TOKEN = "d3bfd48a-bced-4a58-a58b-4094da934cf1";
module.exports = event => {
const distancia = event.data.distancia;
return fetch(getRestEndpoint(distancia, API_TOKEN))
.then(response => response.json())
.then(data => {
const abarrotes = [];
for (let item in data) {
abarrotes.push({
id: data[item].Id,
nombre: data[item].Nombre,
latitud: data[item].Latitud,
longitud: data[item].Longitud
});
}
console.log(abarrotes);
return { data: abarrotes };
});
};
function getRestEndpoint(query) {
return `http://www3.inegi.org.mx/sistemas/api/denue/v1/consulta/buscar/abarrotes/21.85717833,-102.28487238/${query}/${API_TOKEN}`;
}
And my Query is the following:
query {
feed(distancia: 400) {
id
nombre
latitud
longitud
}
}
By the way, im working on the graph.cool platform!
This had nothing to do with GraphQL/GraphCool, I just needed to parseFloat() the values which I'm receiving as a string, and then push it to the array.
latitud: parseFloat(data[item].Latitud),
longitud: parseFloat(data[item].Longitud)