The back-end generated the data API, and how to fetch data on the front end
ps: I use react
URL: http://localhost:8080/api/barrages
when request the above url, the browser displays as follows.
{
"content": [
{
"key": 12344443434545435,
"text": "绿色走一波",
"time": 500,
"fontFamily": null,
"fontsize": null,
"color": "#0f0",
"video_id": null,
"creationDateTime": "2019-04-08T13:59:51Z"
}
],
"page": 0,
"size": 30,
"totalElements": 1,
"totalPages": 1,
"last": true
}
Front-end: get data
fetch("/api/barrages", { method: 'GET' })
.then(function (res) {
res.json()
.then(function (barrage) {
console.log(barrage);
}
)
})
I want to get the data of content
You would need to do it like this:
fetch("/api/barrages", { method: 'GET' })
.then(function (res) {
return res.json()
}
.then(function(myJson){
console.log(JSON.stringify(myJson))
})
})
Related
I am querying the Imgix Management API with no issue. I can retrieve an individual asset and a list of assets. However, most of the data properties are null. It looks like this:
{
"data": {
"attributes": {
"analyzed_content_warnings": null,
"analyzed_faces": null,
"analyzed_tags": null,
"categories": null,
"color_model": null,
"color_profile": null,
"colors": null,
"content_type": "image/jpeg",
"custom_fields": null,
"date_created": 1667935028,
"date_modified": null,
"description": null,
"dpi_height": null,
"dpi_width": null,
"face_count": null,
"file_size": 1016205,
"has_frames": null,
"media_height": null,
"media_kind": "IMAGE",
"media_width": null,
"name": null,
"origin_path": "/test/roses.jpeg",
"source_id": "XXXXXXXXXXXXXXXXXXXX",
"tags": null,
"uploaded_by": null,
"uploaded_by_api": false,
"warning_adult": null,
"warning_medical": null,
"warning_racy": null,
"warning_spoof": null,
"warning_violence": null
},
"id": "XXXXXXXXXXXXXXXXXXX/test/roses.jpeg",
"type": "assets"
},
"included": [],
"jsonapi": {
"version": "1.0"
},
"meta": {
"authentication": {
"authorized": true,
"clientId": null,
"mode": "PUBLIC_APIKEY",
"modeTitle": "Public API Key",
"tag": "XXXXXXXXXXXXXXX",
"user": null
},
"server": {
"commit": "7c78ee15",
"status": {
"healthy": true,
"read_only": false,
"tombstone": false
},
"version": "3.187.0"
}
}
}
I'm missing data.colors, data.media_height, data.media_width.
My code is very basic:
import fetch from 'node-fetch'
const imgix_key = 'xxxxxxxx'
const imgix_source_id = 'xxxxxxxx'
const imgix_url = `https://api.imgix.com/api/v1/assets/${imgix_source_id}/test/roses.jpeg`
async function init() {
const method = 'get'
const headers = {
Authorization: `Bearer ${imgix_key}`,
'Content-Type': 'application/x-www-form-urlencoded',
}
const response = await fetch(imgix_url, { headers, method })
const body = await response.text()
console.log(body)
}
init()
I can access data.colors if I request this image from the rendering API with the palette=json parameter, so I know the property theoretically exists.
Request to https://xxxxxxx.imgix.net/test/roses.jpeg?palette=json:
{
"colors":[
{
"red":0.960784,
"hex":"#f5ece9",
"blue":0.913725,
"green":0.92549
},
{
"red":0.843137,
"hex":"#d7cb99",
"blue":0.6,
"green":0.796078
},
{
"red":0.768627,
"hex":"#c44535",
"blue":0.207843,
"green":0.270588
},
{
"red":0.670588,
"hex":"#aba544",
"blue":0.266667,
"green":0.647059
},
{
"red":0.454902,
"hex":"#746a4f",
"blue":0.309804,
"green":0.415686
},
{
"red":0.227451,
"hex":"#3a452f",
"blue":0.184314,
"green":0.270588
}
],
"average_luminance":0.387471,
"dominant_colors":{
"vibrant":{
"red":0.698039,
"hex":"#b2524d",
"blue":0.301961,
"green":0.321569
},
"muted_light":{
"red":0.823529,
"hex":"#d2b3aa",
"blue":0.666667,
"green":0.701961
},
"muted":{
"red":0.698039,
"hex":"#b2524d",
"blue":0.301961,
"green":0.321569
},
"vibrant_dark":{
"red":0.368627,
"hex":"#5e220c",
"blue":0.0470588,
"green":0.133333
},
"vibrant_light":{
"red":0.898039,
"hex":"#e5c699",
"blue":0.6,
"green":0.776471
},
"muted_dark":{
"red":0.305882,
"hex":"#4e3529",
"blue":0.160784,
"green":0.207843
}
}
}
I've tried adding a fields parameter, like this:
https://api.imgix.com/api/v1/assets/xxxxxxxxxxxxxx/test/roses.jpeg?fields[assets]=name,origin_path,colors,media_width,media_height
I get the specified properties, but they're still null.
Could anyone help me understand why these properties are coming back null?
I would like to write a prebuild script to cache the image metadata so I can set image dimensions and colorful placeholder blocks.
Thanks
I would encourage you to write into our support team (support#imgix.com) with this issue. The reason these fields return null is likely tied to your account/Source settings, which they can help you navigate. Hope that helps.
I try to type a Promise.
Funcrion's code:
const getActivityLists = async () => {
try {
//let res: Promise<Item[]>
let res: Promise<any>
if (currentPlanValue !== null) {
res = await getPlanActivityList(currentPlanValue.id)
} else {
res = await getActivitiesLists()
}
console.log(res)
createCodesList(res.data)
} catch (error) {
console.log(error)
}
}
The problem is in the 'res.data'.
The network output looks like array of objects that I need.
But if I output 'res' to console, I have this:
{
"data": [
{
"id": "f62b5c25-0d98-4b49-9706-8516875e5527",
"name": "Стажировка 2",
"description": "Как проходить стажировки",
"archive": false,
"activites": [
{
"directionId": "edf8c771-3b01-49c8-84a0-6cf4ed900370",
"activeId": "62b4c56b-3863-4373-8255-3cca6e70d478",
"order": 1,
"name": "DKO"
},
{
"directionId": "4765d688-bc40-4c4f-b039-2dc4b16d3b7c",
"activeId": "cb11db28-d7eb-413a-9348-f253a113c137",
"order": 2,
"name": "STAZH"
},
{
"directionId": "cd5bb29d-c17d-47cb-9a05-ae121c7958fc",
"activeId": "fa547f06-b00a-49fa-b647-0186b8cd3931",
"order": 3,
"name": "REGION"
}
],
"createdAt": "2022-10-28T11:04:28.924Z",
"updatedAt": "2022-10-28T11:04:28.947Z",
"activeId": "27718a9e-706d-4e23-940b-dbd10da3c5b8",
"userId": null,
"historyId": null
}
],
"status": 200,
"statusText": "OK",
"headers": {
"content-length": "4584",
"content-type": "application/json; charset=utf-8"
},
"config": {
"transitional": {
"silentJSONParsing": true,
"forcedJSONParsing": true,
"clarifyTimeoutError": false
},
"transformRequest": [
null
],
"transformResponse": [
null
],
"timeout": 0,
"xsrfCookieName": "XSRF-TOKEN",
"xsrfHeaderName": "X-XSRF-TOKEN",
"maxContentLength": -1,
"maxBodyLength": -1,
"env": {
"FormData": null
},
"headers": {
"Accept": "application/json, text/plain, */*"
},
"method": "get",
"url": "http://localhost:3000/activitesList/list"
},
"request": {} }
My array is inside 'data', so I have to pass res.data into function 'createCodesList'.
When I try to type my 'res', I get error:
Property 'data' does not exist on type 'Promise'
How to fix it?
I don't have any idea why Promise doesn't work.
'any' means that inside promise can be anything, doesn't it?
But of course in future I want to type 'res' by my oun type Item[]. It also don't work now.
Type of your response is actual response not a promise as you already awaiting the result so
let res: Promise<any>
should be changed to
let res: any
Or as T.J. Crowder in the comment change it to actual response type
let res:{data:any} //any should be replace with actual model and other properties should be added alongwith data
I am trying to parse responses back from the following fetch api calls. I am able to display the response as a string, but I would like to get specific properties from the json blob and I am struggling to do so. I am not sure how to access the json object properties inside the Response Object.
This is for a cloudflare worker using ES6.
The Json structure is here: json response
{
"success": true,
"errors": [],
"messages": [],
"result": {
"id": "699d98642c564d2e855e9661899b7252",
"created_on": "2014-01-01T05:20:00.12345Z",
"modified_on": "2014-01-01T05:20:00.12345Z",
"name": "server-1",
"description": "Health check for www.example.com",
"suspended": false,
"notification": {
"suspended": false,
"email_addresses": [
"alert#example.com",
"oncall#example.com"
],
"trigger": "FAIL"
},
"check_regions": [
"WEU",
"ENAM"
],
"type": "HTTPS",
"consecutive_successes": 1,
"consecutive_fails": 1,
"http_config": {
"method": "GET",
"port": 80,
"path": "/health",
"expected_codes": [
"2xx",
"302"
],
"expected_body": "success",
"follow_redirects": false,
"allow_insecure": false,
"header": {
"Host": [
"example.com"
],
"X-App-ID": [
"abc123"
]
}
},
"tcp_config": {
"method": "connection_established",
"port": 80
},
"timeout": 5,
"retries": 2,
"interval": 60,
"address": "www.example.com",
"status": "healthy",
"failure_reason": ""
}
}
const fw1aUrl = "https://api.cloudflare.com/client/v4/zones/<>/healthchecks/<>"
const fw1bUrl = "https://api.cloudflare.com/client/v4/zones/<>/healthchecks/<>"
let temp = {}
async function handleRequest() {
const init = {
headers: {
"content-type": "application/json;charset=UTF-8",
"X-AUTH-EMAIL": CLOUDFLARE_API_EMAIL,
"X-AUTH-KEY": CLOUDFLARE_API_KEY,
},
}
const [fw1aResponse, fw1bResponse] = await Promise.all([
fetch(fw1aUrl,init),
fetch(fw1bUrl,init)
]);
const fw1aresult = await fw1aResponse.json()
const fw1bresult = await fw1bResponse.json()
temp.fw1a = await fw1aresult
temp.fw1b =await fw1bresult
const jsonobj = await JSON.parse(temp)
console.log(jsonobj)
return jsonobj
}
addEventListener("fetch", event => {
const obj = handleRequest()
console.log(obj.fw1a.result)
console.log(obj.fw1b.result)
return event.respondWith(new Response("hello"))
})
})
I am trying to download the tar file in node-red.
Following is my JavaScript code to download the file.
downloadTar(sendObj).then(res => {
var bytes = new Uint8Array(byte); // pass your byte response to this constructor
var blob = new Blob([bytes], {type: "application/tar"});
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
var fileName = 'genome.tar';
link.download = fileName;
link.click();
});
function downloadTar(data) {
return new Promise((resolve, reject) => {
$.ajax({
url: nodeRedDownloadTar,
type: 'POST',
data: data,
success: function (result) {
resolve(result);
}
});
});
}
Following is my Node-Red flow, I am reading the file in a single Buffer Object and sending it to the http response
Then following is the response I am getting it from the backend.
The problem is the tar file is not getting downloaded. I am not sure where I am making the problem.
The following flow is working properly, I'm using the headers option in the http-response node to set the content-type to appplication/x-tar
[
{
"id": "6e993a09.f44244",
"type": "file in",
"z": "1c834717.22be01",
"name": "",
"filename": "/home/pi/test.tar",
"format": "",
"chunk": false,
"sendError": false,
"encoding": "none",
"x": 600,
"y": 580,
"wires": [
[
"6e7d5f6f.c9477"
]
]
},
{
"id": "df49df3b.d325b",
"type": "http in",
"z": "1c834717.22be01",
"name": "",
"url": "/tar",
"method": "post",
"upload": false,
"swaggerDoc": "",
"x": 380,
"y": 580,
"wires": [
[
"6e993a09.f44244"
]
]
},
{
"id": "6e7d5f6f.c9477",
"type": "http response",
"z": "1c834717.22be01",
"name": "",
"statusCode": "",
"headers": {
"content-type": "application/x-tar"
},
"x": 800,
"y": 580,
"wires": []
}
]
I can successfully fill my datatable with ajax call, but then I don't know how to parse JSON that is received by datatable with this ajax call.
Here is my JavaScript code, that makes ajax call to the server and fills my datatable correctly:
$('#transactions').DataTable({
"processing": true,
"ajax": {
"url": "/transactions
},
"columns": [
{ "data": "car"},
{ "data": "card_number"},
{ "data": "invoice"},
{ "data": "status"}
]
});
This is the JSON object returned from the server:
{
"data": [
{
"car": 190,
"card_number": "6395637",
"invoice": 200,
"status": "success"
},
{
"car": 191,
"card_number": "9473650",
"invoice": 180,
"status": "success"
}
],
"balance": 7300
}
As you can see, the data parameter of the returned JSON object is used by the datatables function to fill by datatables, and now I want to parse the balance parameter, but I can't. How can i achieve this?
Something like this:
$('#transactions').dataTable({
"ajax" : {
"url" : "/transactions",
"dataSrc" : function (json) {
// manipulate your data (json)
...
// return the data that DataTables is to use to draw the table
return json.data;
}
}
});
Docs: https://datatables.net/reference/option/ajax.dataSrc
Don't use the url feature of DataTable, make the Ajax call yourself
$.getJSON('/transactions', function(response) {
$('#transactions').dataTable({
processing: true,
data: response.data,
columns: [
{ data: "car"},
{ data: "card_number"},
{ data: "invoice"},
{ data: "status"}
]
});
window.someGlobalOrWhatever = response.balance
});
Since DataTables 1.10, you may use the ajax.json() function: https://datatables.net/reference/api/ajax.json()
I have implemented it in the example code below.
$( document ).ready(function() {
$('#search-form').submit(function(e) {
e.preventDefault();
var table = $('#location-table').DataTable({
destroy: true,
ajax: "/locations.json",
columns: [
{ "data": "code" },
{ "data": "status" },
{ "data": "name" },
{ "data": "region" },
{ "data": "address" },
{ "data": "city" },
{ "data": "state" },
{ "data": "zip" },
{ "data": "phone_number" },
]
})
table.on( 'xhr', function () {
var json = table.ajax.json();
$('#totals').text(json.totals)
});
})
});
NOTE for this to work you must initialize the datatable with $('#location-table').DataTable() and not $('#location-table').dataTable (the difference being the capitalized D)