How to display images from API using Fetch API? - javascript

First of all, I'm working with the Unofficial Xbox API and I'm trying to display the images from the endpoint example CLICK HERE that is provided inn the website.
So I'm using a button with callback to a Fetch API function:
document.getElementById('getScreenshots').addEventListener('click', getScreenshots);
function getScreenshots(){
// Get data from URL
fetch('https://xboxapi.com/v2/screenshots/1144039928',{
headers: new Headers({
"X-Auth": "HERE-GOES-MY-API-KEY",
"Content-Type": "application/json",
})
})
.then((res) => res.json())
.then((data) => {
let output = '<h5>List of Recent Screenshots</h5>';
data.forEach(function(screenshot){
output += `
<ul>
<li>ID: ${screenshot.screenshotId}</li>
<li>Published at: ${screenshot.datePublished}</li>
<li><img src="${screenshot.uri}"></li>
</ul>
`;
});
document.getElementById('screenshots').innerHTML = output;
})
.catch((err) => console.log(err))
}
<button id="getScreenshots">Get Screenshots</button>
<ul id="screenshots"></ul>
but everytime that I try to request it, the images are not shown and the console trows me an error of 404 for each image. Here is what I'm talking about:
Can anybody help me with this?.
Thanks in advance.
UPDATE, this is the json data that I get when using Postman:
"thumbnails": [
{
"uri": "https://screenshotscontent-t5002.xboxlive.com/xuid-2535443387655711-public/29cd392a-6758-4926-8396-44aa77822ac6_Thumbnail.PNG",
"fileSize": 0,
"thumbnailType": "Small"
},
{
"uri": "https://screenshotscontent-t5002.xboxlive.com/xuid-2535443387655711-public/29cd392a-6758-4926-8396-44aa77822ac6_Thumbnail.PNG",
"fileSize": 0,
"thumbnailType": "Large"
}
],
"screenshotUris": [
{
"uri": "https://screenshotscontent-d5002.xboxlive.com/xuid-2535443387655711-private/29cd392a-6758-4926-8396-44aa77822ac6.PNG?sv=2015-12-11&sr=b&si=DefaultAccess&sig=5Is2Shl9m0c85yI0Vq%2BTRs3cuwYDvUR2BBWrD2%2FpkIw%3D",
"fileSize": 1255362,
"uriType": "Download",
"expiration": "2018-08-29 04:51:56"
}
],
"xuid": 2535443387655711,
"screenshotName": "",
"titleName": "Halo: The Master Chief Collection",
"screenshotLocale": "en-US",
"screenshotContentAttributes": "None",
"deviceType": "Durango",
"screenshotDetails": "https://xboxapi.com/v2/2535443387655711/screenshot-details/d1adc8aa-0a31-4407-90f2-7e9b54b0347c/29cd392a-6758-4926-8396-44aa77822ac6"
},

screenshot.screenshotUris.uri will be undefined because screenshot.screenshotUris is an array. So you need:
screenshot.screenshotUris[0].uri
or making a cycle like
screenshot.screenshotUris.forEach(function(el) { ...el.uri... })

Related

Invalid Request Body in Viewsonic Myviewboard Open API Broadcast Message

I am trying to send a standard/urgent message to my Viewsonic TV using its Open API
everything is working fine but when I try sending a message that is longer than 16 characters, I am getting an error message that says {message: 'Invalid Request Body'}.
I am realy confused as to why this is happening, it clearly says on the documentation that 300 characters is maximum for standard message.
Here is the sample snippet that I have
//this one can be converted using JSON.stringify()
const inputBody = '{
"deviceIds": [
"8jy9sne7-esbu-qrf7-d62f-c46srimnjcnn"
],
"entityId": "o39onp8a-um26-dgxf-v3iy-4xqqr2aqzw2h",
"message": "Hello world This is a really long message",
"type": "standard",
"siren": false,
"loops": 2
}';
const headers = {
'Content-Type':'application/json',
'Accept':'application/json',
'Authorization':'bearer ************'
};
fetch('https://oapi.myviewboard.com/devices/broadcast',
{
method: 'POST',
body: inputBody,
headers: headers
})
.then(function(res) {
return res.json();
}).then(function(body) {
console.log(body);
});
Also, I noticed on the sample code from the documentation, what does this symbol mean u)s]? Maybe it has something to do with this issue.
const inputBody = '{
"deviceIds": [
"8jy9sne7-esbu-qrf7-d62f-c46srimnjcnn",
"jb9a2hpd-h2qc-hp9m-4i36-2m5wzqmn7o9w"
],
"entityId": "o39onp8a-um26-dgxf-v3iy-4xqqr2aqzw2h",
"message": "u)s]",
"type": "standard",
"siren": true,
"loops": 84479723
}';

Fetch response db.json is one object instead an array of objects

I am trying to display on a single page react app, the icons from items, but as a response from the fetch, instead of getting an array of objects, I'm getting only one object, which doesnt have the data from my db.json.
My question is: How can I reach the "displayIcon" if I can't get a correct response?
Here is my function, and below the db.json:
const [weapons, setWeapons] = useState(null);
useEffect(() => {
console.log('effect triggered');
fetch('http://localhost:3001/data/', {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
})
.then((res) => res.json())
.then((data) => setWeapons(data));
}, []);
console.log('render', weapons)
"data": [
{
"uuid": "1",
"displayName": "Odin",
"category": "EEquippableCategory::Heavy",
"defaultSkinUuid": "f454efd1-49cb-372f-7096-d394df615308",
"displayIcon": "https://media.valorant-api.com/weapons/63e6c2b6-4a8e-869c-3d4c-e38355226584/displayicon.png",
"killStreamIcon": "https://media.valorant-api.com/weapons/63e6c2b6-4a8e-869c-3d4c-e38355226584/killstreamicon.png",
"assetPath": "ShooterGame/Content/Equippables/Guns/HvyMachineGuns/HMG/HMGPrimaryAsset",
},
{
"uuid": "2",
"displayName": "Ares",
"category": "EEquippableCategory::Heavy",
"defaultSkinUuid": "5305d9c4-4f46-fbf4-9e9a-dea772c263b5",
"displayIcon": "https://media.valorant-api.com/weapons/55d8a0f4-4274-ca67-fe2c-06ab45efdf58/displayicon.png",
"killStreamIcon": "https://media.valorant-api.com/weapons/55d8a0f4-4274-ca67-fe2c-06ab45efdf58/killstreamicon.png",
"assetPath": "ShooterGame/Content/Equippables/Guns/HvyMachineGuns/LMG/LMGPrimaryAsset",
}
If you are trying to render a single image, you can get the item by uuid and render the image (or anything else).
Here's an example component That accesses the weapon with uuid of 2. In your app you'd probably want to pass uuid to this component using props, but the same logic will apply.strong text
// get weapon by uuid
const ShowIcon = () => {
let weapons = {
"data": [
{
"uuid": "1",
"displayName": "Odin",
"category": "EEquippableCategory::Heavy",
"defaultSkinUuid": "f454efd1-49cb-372f-7096-d394df615308",
"displayIcon": "https://media.valorant-api.com/weapons/63e6c2b6-4a8e-869c-3d4c-e38355226584/displayicon.png",
"killStreamIcon": "https://media.valorant-api.com/weapons/63e6c2b6-4a8e-869c-3d4c-e38355226584/killstreamicon.png",
"assetPath": "ShooterGame/Content/Equippables/Guns/HvyMachineGuns/HMG/HMGPrimaryAsset",
},
{
"uuid": "2",
"displayName": "Ares",
"category": "EEquippableCategory::Heavy",
"defaultSkinUuid": "5305d9c4-4f46-fbf4-9e9a-dea772c263b5",
"displayIcon": "https://media.valorant-api.com/weapons/55d8a0f4-4274-ca67-fe2c-06ab45efdf58/displayicon.png",
"killStreamIcon": "https://media.valorant-api.com/weapons/55d8a0f4-4274-ca67-fe2c-06ab45efdf58/killstreamicon.png",
"assetPath": "ShooterGame/Content/Equippables/Guns/HvyMachineGuns/LMG/LMGPrimaryAsset",
}
]
}
let weapon = weapons.data.filter(i => i.uuid == 2 ? 1 : 0);
return(
<div>
<img src={weapon[0].displayIcon} />
</div>
);
}
ReactDOM.render(<ShowIcon />, document.getElementById('icon'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="icon"></div>

Error: invalid conference type value while creating event with google meet link

I configured calendar API in my web application and it is working fine. I wanted to add google meet link while creating event. After reading docs I added following code:
'conferenceDataVersion' => 1,
'conferenceData' => [
'createRequest' => [
'conferenceSolutionKey' => [
'type' => 'eventNamedHangout'
],
'requestId' => 'sample232212'
]
],
I am getting error:
{
"error": {
"errors": [
{
"domain": "global",
"reason": "invalid",
"message": "Invalid conference type value."
}
],
"code": 400,
"message": "Invalid conference type value."
}
}
I also try with "eventHangout" and "hangoutsMeet" as per the docs but no luck. I am using google service account. Any help would be highly appreciable.
The object shouldnt contain arrays
"conferenceData": {
"createRequest": {
"conferenceSolutionKey": { "type": "eventNamedHangout" },
"requestId": "randomvalue"
}
}
Issue:
You are adding conferenceDataVersion to the request body, when it's actually a request parameter.
Solution:
Remove conferenceDataVersion from the request body:
'conferenceData' => [
'createRequest' => [
'conferenceSolutionKey' => [
'type' => 'hangoutsMeet'
],
'requestId' => 'sample232212'
]
],
And add it as an additional parameter when making the request:
$optParams = ['conferenceDataVersion' => 1];
$service->events->insert($calendarId, $postBody, $optParams);
Reference:
Events: insert > Parameters
PHP library: Events.insert

TypeError: Cannot read property 'url' of undefined react strapi in JSON object

I'm using strapi with react. I'm fetching a JSON object (home). If I do console.log(home) I get:
{
"id": 6,
"created_at": "2020-06-21T07:07:36.000Z",
"updated_at": "2020-06-21T07:18:40.000Z",
"HomeTextTop": "Home text here.",
"HomeTitle": "Home title here",
"Hero": {
"id": 3,
"name": "facade_pastel_summer_123664_800x600",
"alternativeText": "",
"caption": "",
"width": 800,
"height": 600,
"url": "http://someurlhere.com"
}
}
If I console.log(home.Hero) I get the appropriate:
{
"id": 3,
"name": "facade_pastel_summer_123664_800x600",
"alternativeText": "",
"caption": "",
"width": 800,
"height": 600,
"url": "http://someurlhere.com"
}
However, if I drill down and try and get just the URL console.log(home.Hero.url) I get this error:
TypeError: Cannot read property 'url' of undefined react strapi in JSON object
What am I missing here?
The 'action' fetching code is:
export const fetchHome = () => {
return dispatch => {
dispatch(fetchHomeBegin())
return fetch(`${strapiUrl}/home`, {
method: 'get',
mode: 'cors',
headers: { 'Content-Type': 'application/json' }
})
.then(res => res.json())
.then(json => {
console.log(json)
dispatch(fetchHomeSuccess(json))
})
.catch(error => dispatch(fetchHomeFail(error)))
}}
And JSON.stringify(home.Hero) gives the same result in string form
Here's what's happening.
This is likely because at the moment of reading url from Hero, Hero is
not yet defined (as the error message suggests). You could tackle this
by first confirming Hero is defined before reading url. Something like
this: console.log(home.Hero && home.Hero.url).
Though this leads to a lot of cumbersome code, and therefor (imo) it
would be better to use https://www.npmjs.com/package/immutable to
manage the data that is returned from the Strapi api.
You would then set home as an immutable object (a Map) and read url
like this: console.log(home.getIn([‘Hero’, ‘url’]). If Hero is
undefined here your application will not crash, but instead false will
be returned. - Boaz Poolman - slack.strapi

Contentful API returning 'version mismatch' on entry update

I'm attempting to do the following with the Content Management API for Contentful:
Get an entry (entry1)
Find another entry (entry2) using data from a field in entry1
Update entry1 with data from entry2
My code looks like this:
client.getSpace("xxxxxxxx").then(function(space){
space.getEntries({
"content_type": "xxxxxxxx",
"sys.id": "2KEZYJOgDSeQMCQIE0Oo88",
"limit": 1
}).then(function(places){
//search for relevant category entry
space.getEntries({
"content_type": contentType.category,
"sys.id": places[0].fields.category["en-GB"],
"limit": 1
}).then(function(category){
//update place object
places[0].fields.categoryNew = {
"en-GB": [
{ sys: { type: "Link", linkType: "Entry", id: category[0].sys.id } }
]
};
//update place
request({
method: 'PUT',
url: 'https://api.contentful.com/spaces/xxxxxxxx/entries/' + places[0].sys.id,
headers: {
'Authorization': 'Bearer xxxxxxxx',
'Content-Type': 'application/vnd.contentful.management.v1+json',
'X-Contentful-Content-Type': 'xxxxxxxx'
},
body: JSON.stringify({fields:places[0].fields})
}, function (error, response, body) {
console.log(body);
});
});
});
});
Steps 1 and 2 work fine but the final step, updating the original entry, keeps returning the following error:
Response: {
"sys": {
"type": "Error",
"id": "VersionMismatch"
},
"requestId": "content-api:2PSSF6RtpSs2YyaaisK2wc"
}
How do I stop this happening? I've tried everything I can think of including manually updating the sys.version number, but when updating it seems to ignore any sys data I provide.
Refer to https://www.contentful.com/developers/docs/references/content-management-api/#/introduction/updating-and-version-locking
You need to pass the version as a header parameter called "X-Contentful-Version" with the PUT request.

Categories

Resources