I have JS object in the following format which i want to send at backend. I have implemented some code but at nodeJs controller it says hotel is undefined. My written code is following:
let hotel = new FormData();
hotel.append('name', data.append);
hotel.append('slug', data.slug);
hotel.append('logo', data.logo);
hotel.append('coverAvatar', data.coverAvatar);
hotel.append('designs', [{ name: `${+new Date()}`, url: localStorage.getItem('initialDesign') }])
hotel.append('products', [...selectedVariants]);
axios.post(`${baseURL}/hotel`, { hotel },{
headers: {
'Authorization': localStorage.getItem('_AUTH_TOKEN'),
'Content-Type': 'multipart/form-data'
}})
.then(response => {
console.log({ response });
})
.catch(err => {
console.log('err', err);
})
I'm using multipart/form-data because logo and coverAvatar are output of <input type='file' />
My data Format
{
"name": "preshan hotel 2",
"logo": {file},
"coverAvatar": {file},
"romms": [{
"name": "tempDesign",
"url": "https://picsum.photos/600/800"
}],
"facilities": [
{ "facilityId": "61ceb3931b1b68fe90827f23", "facilityMappings": ["61ceb39b1b1b68fe90827f2c", "61ceb39b1b1b68fe90827f41"] },
{ "facilityId": "61ceb3ca1b1b68fe90827f47", "facilityMappings": ["61ceb3ca1b1b68fe90827f50","61ceb3ca1b1b68fe90827f58", "61ceb3ca1b1b68fe90827f56"] },
{ "facilityId": "61ceb3e41b1b68fe90827f5d", "facilityMappings": ["61ceb3e41b1b68fe90827f5f"]}
]
}
You should pass your formdata directly instead of passing an object.
In your example it would look like this:
...
axios.post(`${baseURL}/hotel`, hotel,{
...
Related
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
}';
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>
I'm very new to React. I have a JSON response that is being returned to me VIA WebAPI 2.
I would like to display only parts of this reply, for example if i only want to display the title
I have implemented the following code, but when view title it shows up as undefined
App.js
class App extends React.Component {
constructor(props){
super(props);
this.state = {reply: ""}
this.callAPI = this.callAPI.bind(this);
}
componentDidMount(){
this.callAPI();
}
callAPI(){
fetch('http://localhost:51092/api/COM',{
method:'get',
headers:{'Content-Type':'application/json'}
}).then(function(response){
return response.json();
}).then(responseData => {
this.setState({reply:responseData});
console.log("REPONSEDATA-----"+responseData);
console.log(responseData.title);
});
}
render(){
return(
<div>
</div>
);
}
}
Update 1
callAPI(){
fetch('http://localhost:51092/api/COM',{
method:'get',
headers:{'Content-Type':'application/json'}
}).then(response =>{
return response.json().then(responseData => {
this.setState({reply:responseData});
console.log("RESPONSE----"+JSON.stringify(responseData));
console.log(responseData.title);
});
});
}
API JSON Response
[{
"fileVer": {
"type": "specific",
"fileId": {
"type": "specific",
"internalId": 1,
"externalId": null
},
"internalVersion": 2,
"externalVersion": null,
"versionSortKey": "0"
},
"title": "1576544 Alberta Ltd._Annual Returns_2012-01-03",
"extension": "pdf",
"logicalSize": "47872",
"sizePrecision": "exact",
"createdAtUtc": "2019-05-27T15:22:41.510Z",
"lastAccessedAtUtc": "2019-07-10T21:00:28.029Z",
"lastWrittenAtUtc": "2019-05-27T15:17:48.000Z",
"changedAtUtc": "2019-05-27T15:17:48.000Z",
"fileGuid": "{881D8975-84B9-4A73-9AFF-F0C61C94FE90}",
"checksumMD5": "24f6badff8b70783697e0052fc4a7fe6",
"fileMissing": false,
"contentIsVolatile": false
}][{
"fileVer": {
"type": "specific",
"fileId": {
"type": "specific",
"internalId": 2,
"externalId": null
},
"internalVersion": 3,
"externalVersion": null,
"versionSortKey": "0"
},
"title": "1576544 Alberta Ltd._By-Law #1_",
"extension": "pdf",
"logicalSize": "951046",
"sizePrecision": "exact",
"createdAtUtc": "2019-05-27T15:22:42.000Z",
"lastAccessedAtUtc": "2019-07-10T21:02:54.062Z",
"lastWrittenAtUtc": "2019-05-27T15:16:28.000Z",
"changedAtUtc": "2019-05-27T15:16:28.000Z",
"fileGuid": "{F8B54DB0-7E9F-4F0F-8ABA-D03C1DE4FF8C}",
"checksumMD5": "ffe728ef1a87f0cec7737b6d224bb50d",
"fileMissing": false,
"contentIsVolatile": false
}]
Not sure what im doing wrong here, ive used Ajax a lot so maybe im confusing what can be done with react and fetch
Update 2
So it seems that this may be a single object, and not an array of objects.
console.log("RESPONSE----"+JSON.stringify(responseData));
var arr = [];
console.log("KEYS"+Object.keys(responseData));
Object.keys(responseData).forEach(function(key){
console.log(responseData[key]);
arr.push(responseData[key]);
When i try to access responseData[key] i end up getting a single letter, and not a property from the json response
This pushes me to believe that this is not an array of objects but a single object
you should use JSON.stringify when printing full json response and if part of the object is string (eg... response.title then its ok but if not you can try .toString() or JSON.stringify)
callAPI(){
fetch('http://localhost:51092/api/COM',{
method:'get',
headers:{'Content-Type':'application/json'}
}).then(function(response){
return response.json().then((responseData)=>{
this.setState({reply:responseData});
console.log("REPONSEDATA----"+JSON.stringify(responseData));
console.log(responseData.title);
return responseData
});
}
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... })
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.