Cannot access JSON Properties within an HTTP POST Response - javascript

I am calling an HTTP POST Request, the response is JSON data.
POST Request:
const postXHR = new XMLHttpRequest();
postXHR.open('POST', postOptions);
postXHR.setRequestHeader("Accept", "text/json");
postXHR.setRequestHeader("Content-Type", "text/json");
postXHR.onreadystatechange = function() {
const response = postXHR.response;
if (response.response) {
console.log(postXHR.status);
}
createNewOptionValues(response);
}
postXHR.send('{"optionName":"optionName46", "platformName":"platformName46","dotDigitalId":3,"googleId":4}');
POST Response/JSON Data:
{
"data": {
"rooftopGoogleOptionId": 99,
"googleId": 4,
"dotDigitalId": 3,
"optionName": "optionName46",
"optionValue": null,
"platformName": "platformName46",
"googleAccount": null,
"dotDigitalAccount": null,
"updatedBy": null,
"updatedAt": null,
"createdBy": "root",
},
"status": 201,
"message": "success"
}
The createNewOptionValue function should log the value of a property within the response.
function createNewOptionValues(obj){
console.log(obj.googleId);
console.log(obj['googleId']);
}
Yet, the output is undefined, when using console.log(obj), the response does show.

When you receive a response, it is in "text" format (in most of the cases)
So you need to pass that response to JSON.parse for accessing it as a JSON Object.
Adding just 1 line in your createNewOptionValues function will make it work. Also, you need to access obj.data.googleId instead of accessing obj.googleId
function createNewOptionValues(obj){
obj = JSON.parse(obj)
console.log(obj.data.googleId);
console.log(obj.data['googleId']);
}

Related

Post Json with axios to Strapi

I have a backend strapi-service and i try to post a JSON to it with axios. It creates the new Content with an ID, but the JSON is empty. As a response it returns null.
I am using react-js. My Code:
import axios from 'axios';
function App() {
const apiUrl = 'http://localhost:1338/api/participants'
const posting = async () => {
await axios.post(apiUrl,{
"data": {
"startStudyTime": 0,
"endStudyTime": 0,
"objectsPressed": [{}],
"searchHistory": [{}],
"connection": {
"Device": "",
"Browser": "",
"OS": ""
},
"finished": false,
"canceled": false
}
}, { headers: { 'Content-Type': 'application/json' } })
.then( response =>{
console.log('response.data:', response.data)
console.log('response.data.data:', response.data.data)
console.log('response.data.data.id:', response.data.data.id)
})
}
return (
<div className="App">
<button onClick={posting}>Submit</button>
</div>
);
}
export default App
The code runs and when I press on the submit-button, I'll always get a log, where the data has a diffrent id, but the participantLoggingData remains null, as the postman log below.
So i tried to use postman to see if anything is wrong with axios or sth:
I used the "post" call, put the Json object into the body, set the body to raw and JSON and got the following:
{
"data": {
"id": 27,
"attributes": {
"participantLoggingData": null,
"createdAt": "2022-11-07T00:23:41.759Z",
"updatedAt": "2022-11-07T00:23:41.759Z",
"publishedAt": "2022-11-07T00:23:41.759Z"
}
},
"meta": {}
}
and the json is stil null, idk...
I tried stuff like JSON.stringify() this gave me a 400 error and i tried to store the json into a container, so i can all sth like await axios.post(apiUrl, data,{ headers: { 'Content-Type': 'application/json' } }), but nothing worked.
So I looked up the strapi documentation and i couldn't find any diffrence(syntax-wise), so i guess my strapi isn't set up 100% correct. If I create a new contentType with only a Json it has the same issue. Is there a fix for it?
My strapi configs:
Under Settings/Roles/Public/Participant, all boxes are checked, so basicly everyone should be able to create, find, update and delete stuff.
My ContentType is called Participant with a JSON named "participantLoggingData"
I also have tried to use the axios.put call, but this doesnt change the object, it still remains empty :/
For json field participantLoggingData in your post request you need to send data like:
{
"data": {
"participantLoggingData": {
"startStudyTime": 0,
"endStudyTime": 0,
"objectsPressed": [{}],
"searchHistory": [{}],
"connection": {
"Device": "",
"Browser": "",
"OS": ""
},
"finished": false,
"canceled": false
}
}
}
You cannot directly pass data in data key in this case.

How to access JS Object value in nestted object?

I am having trouble accessing the data in this JS Object. I can get this data by accessing data.queryParams. But if I try to drill lower, I get undefined. Below is what shows up if I do a JSON.stringify(data.queryParams). I've tried data.queryParams.attributes, data.queryParams[0], data.queryParams.handle, etc. And I get undefined for all of them.
console.log(data)
Object {
"hostname": "127.0.0.1",
"path": null,
"queryParams": Object {
"{\"attributes\":[{\"handle\":\"email\",\"name\":\"Email\",\"value\":\"test#test.com\"},{\"handle\":\"fname\",\"name\":\"First Name\",\"value\":\"Luke\"},{\"handle\":\"lname\",\"name\":\"Last Name\",\"value\":\"Skywalker\"},{\"handle\":\"zip\",\"name\":\"Postal Code\",\"value\":\"73067-9895\"},{\"handle\":\"uuid\",\"name\":\"Unique Identifier\",\"value\":\"XXXXXXXXXXXX\"}],\"status\":[{\"group\":\"penguins\",\"subgroups\":[\"King penguins\"],\"verified\":true}]}": "",
},
"scheme": "exp",
}
console.log(data.queryParams)
Object {
"{\"attributes\":[{\"handle\":\"email\",\"name\":\"Email\",\"value\":\"test#test.com\"},{\"handle\":\"fname\",\"name\":\"First Name\",\"value\":\"Luke\"},{\"handle\":\"lname\",\"name\":\"Last Name\",\"value\":\"Skywalker\"},{\"handle\":\"zip\",\"name\":\"Postal Code\",\"value\":\"73067-9895\"},{\"handle\":\"uuid\",\"name\":\"Unique Identifier\",\"value\":\"42e97018b6604fe491b82b629ad65c23\"}],\"status\":[{\"group\":\"penguins\",\"subgroups\":[\"King penguins\"],\"verified\":true}]}": "",
}
i think something wrong with your response, your data is set as key of the Object.
const obj = {
"hostname": "127.0.0.1",
"path": null,
"queryParams": {
// below is your data as key
"{\"attributes\":[{\"handle\":\"email\",\"name\":\"Email\",\"value\":\"test#test.com\"},{\"handle\":\"fname\",\"name\":\"First Name\",\"value\":\"Luke\"},{\"handle\":\"lname\",\"name\":\"Last Name\",\"value\":\"Skywalker\"},{\"handle\":\"zip\",\"name\":\"Postal Code\",\"value\":\"73067-9895\"},{\"handle\":\"uuid\",\"name\":\"Unique Identifier\",\"value\":\"XXXXXXXXXXXX\"}],\"status\":[{\"group\":\"penguins\",\"subgroups\":[\"King penguins\"],\"verified\":true}]}": "",
},
"scheme": "exp",
};
let value = Object.keys(obj.queryParams)[0]; // <-- get your data
value = JSON.parse(value); // <-- set to JSON
console.log(value.attributes) // <-- test log attributes
but better if you can fix the response
Try with JSON.parse to convert your JSON string to an object, then you can access your data
let attributes = JSON.parse(data.queryParams).attributes;
console.log(attributes)

Ignore Hyphen in Javascript (Postman)

Building a RestAPI with Postman.
I have some JSON data:
{
"progress-update": {
"#type": "parallel-progress",
"job": {
"#href": "/api/space/job-management/jobs/4691268"
},
"taskId": 4691268,
"jobName": "Compare Config-4691268",
"state": "DONE",
"status": "SUCCESS",
"percentage": 100,
"data": "<![CDATA[Total requests: 3<br>InSync count : 3<br>OutOfSync count : 0<br>]]>",
"subTask": [
{
I want to pull the "state" value into an environment Variable that i can then use to determine wether to continue on to the next request or wait until the state is DONE.
The problem i'm running into is "progress-update": has a hyphen in it, causing my script to not recognize it.
var jsonData = JSON.parse(responseBody);
pm.environment.set("JobStatus", jsonData.progress-update.state);
Postman returns the following error:
There was an error in evaluating the test script: ReferenceError:
update is not defined
You should be able to access your JSON data with
var jsonData = JSON.parse(responseBody);
pm.environment.set("JobStatus", jsonData['progress-update'].state);
using the object bracket notation

How can I post a container in Storage api from loopback?

I already have declared my datasource ,my model and the connector between these.
My model
{
"name": "container",
"base": "Model",
"idInjection": true,
"options": {
"validateUpsert": true
},
"properties": {},
"validations": [],
"relations": {},
"acls": [],
"methods": {}
}
Datasource
"storage": {
"name": "storage",
"connector": "loopback-component-storage",
"provider": "filesystem",
"root": "./server/storage"
}
My provider
{
"filesystem": {
"root": "./server/storage"
}
}
And the Connector
"container": {
"dataSource": "storage",
"public": true
}
I try posting a object like {"Object":"container1"} into path "./server/storage" but I get the following error from callback.
{
"error": {
"statusCode": 500,
"name": "TypeError",
"message": "Path must be a string. Received undefined",
"stack": "TypeError: Path must be a string. Received undefined.."
}
}
Please who can help me to find my issue? Thanks!
You can also use "name" instead of "Object" as key in your JSON object to create a new container/directory using the API.
POST /api/containers {"name":"container1"}
The way to post a container is, without using the loopback api. Create a folder that is gonna be the container into your provider path (being filesystem).
As simple as that!
If you need a programmatic way to add new containers, let's say for example you want to create a filesystem of sorts for new users. You can use the route below. "Container" is the name I called my Model, you can call yours whatever you'd like.
POST localhost:3000/api/container
Inside the body of the post request you have to have an attribute name and the value of the name can be the new container you're creating. The Strongloop/Loopback documentation, which can be found here, is not accurate and neither is the error you get back when you try to post it with their directions.
"error": {
"statusCode": 500,
"name": "TypeError",
"message": "Path must be a string. Received undefined"
}
An excerpt of the code to send a post request to create a new container is also below.
var request = require("request");
var options = {
method: 'POST',
url: 'http://localhost:3000/api/containers',
body: { name: 'someNewContainer' },
json: true
};
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});

Check if JSON object exist (Postman)

I am trying to write a test in Postman to check if JSON keys are present in the response I received from the server.
The response:
{
"Result": 0,
"ResponseStatus": {
"ErrorCode": null,
"Message": null,
"StackTrace": null,
"Errors": null
},
"ResponseHeader": {
"Succeeded": true,
"Errors": null
},
"SessionId": "XXX-XXX-XXX"
}
I want to check "Results, Errorcode, Message,Succeeded" etc..
Thanks!
You could check the response scheme using:
var jsonData = JSON.parse(responseBody);
tests['response json contain Results'] = _.has(jsonData, 'Results');
According to your response body that you get, You can write simple test script for request under test section.
You need to parse your json response first. The script will look like:
var jsonData = JSON.parse(responseBody);
tests["Succeeded with value true"] = jsonData.ResponseHeader.Succeeded === true;
similarly you can write tests for other checks.For sessionId I would suggest you to check it with sessionId where it gets generated(store it in environment and check with it in this request)

Categories