Errors while trying to "Put" JSON Data - javascript

I am working with the Hubspot API and I am trying to modify the close date of a deal via the "PUT" Method by sending JSON Data. But I am getting errors such as
{ status: 'error', message: 'Invalid input JSON on line 1, column
15: Can not deserialize instance of java.util.ArrayList out of
START_OBJECT token', correlationId:
'b8b47229-184d-40b3-b402-9e3dd684b217', requestId:
'd364fe8dac5e876639928dd0d04045fd' }
This is the code that I have written-
fetch('https://api.hubapi.com/deals/v1/deal/103361780?hapikey=', {
method: 'put',
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json'
},
body: JSON.stringify({"properties":{name: "closedate", "value": 1528744207881}})
}).then(res=>res.json())
.then(res => console.log(res));
This is the JSON Data that I am trying to pass
{
"properties":[
{
"name": "closedate",
"value": 1528744207881
}
]
};
And here is the documentation of making a PUT request via the Hubspot API.
I am able to successfully update the value via POSTMAN.
Any help on this matter would be greatly appreciated.

You are missing brackets - [] and on the backend, they are waiting for an array to deserialize it to Arraylist.
Try fetch with this body:
{"properties":[{"name": "closedate", "value": 1528744207881}]}

Related

How to Generate Google Drive File Copy in a Bulk

I want to create file copies in a bulk with one call, now I am using Google Drive Rest API for copying files.
Code:
copyFileCreation(_id, _fileId, _token) {
console.log({ _id }, { _fileId }, { _token });
fetch(`https://www.googleapis.com/drive/v2/files/${_fileId}/copy`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${_token}`,
'Accept': 'application/json'
},
body: JSON.stringify({
"parents": [{
"id": _id
}],
"title": "Untitle"
}),
}).then(res => res.json()).then(data => {
console.log('copyFileCreation_data', { data });
});
}
How can I achieve my goal?
Reference: https://developers.google.cn/drive/api/v2/reference/files/copy
Have you consulted the documentation? Did you read the part where it says
Files.copy is singular one file per call.
The Batching endpoint might be a solution but that depends upon what you qualify as one call.
Batching will let you nest multiple copy calls into a single HTTP Request, but if you are trying to get around the quota limitations this will not help you as the quota is based upon each of the calls with in the batch request.

POSTing a nested object ruins the encoding in NodeJS Backend

I am having trouble sending JSON data that contains special characters like ` to my Node Express server.
I posted How can I render UTF-8 characters in JSX without using dangerouslySetInnerHTML in 2020 earlier, but I think I am approaching the problem incorrectly.
The Problem:
When I submit my JSON form data using an HTTP Client, my req.body HTMLifies special characters:
// Sending a nested JSON.stringified Object
const response1 = await fetch(
`${baseUrl}/chhands/${granthState.lastChhand.id}/pauris`,
{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
pauri: formattedTuk,
last_pauri_id: granthState.lastPauri?.id,
}),
}
);
Here is a result of the console.logging {pauri: formattedTuk, last_pauri_id: granthState.lastPauri?.id}:
What it looks like on the backend when I submit the nested JSON object:
Here is where the where I am even MORE confused:
Here, instead of sending a nested object, I only send the formattedTuk [Array] object, which looks like:
[
{
line_number: 1,
content_unicode: 'ਆਪ ਅਛਤ ਸਮਰੱਥ ਪ੍ਰਭੁ ਦਈ ਬਡਾਈ ਨਾਮ ।',
content_gs: 'Awp ACq smr`Q pRBu deI bfweI nwm [',
content_transliteration_english:
"aap achhat samara'th prabh dhiee baddaiee naam |",
first_letters: 'ਆਅਸਪਦਬਨ',
thamkis: [],
vishraams: [],
},
];
// Sending the raw array object stringified {}
const response2 = await fetch(
`${baseUrl}/chhands/${granthState.lastChhand.id}/pauris`,
{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(formattedTuk),
}
);
What it looks like on the backend when I submit the ONLY the Array Object:
Other things I've tried:
Used Axios (instead node-fetch) and it gave the same effect
Used POSTMAN and it had the same effect
Double checked my Content-Type and charset but it all looks good.
Here is my Express middleware settings. I was using body-parser before, but it seems that express.json() is giving me the same effect. I've also seen people recommend using qs.stringify() but what I am doing seems fairly simple.
app.use(morgan('tiny'));
app.use(helmet());
app.use(express.json());
app.use(cors());
Updates:
Here is the exact "Copy as Fetch" value:
fetch("http://localhost:1469/api/v1/chhands/53/pauris", {
"headers": {
"accept": "*/*",
"accept-language": "en-US,en;q=0.9",
"content-type": "application/json",
"sec-fetch-dest": "empty",
"sec-fetch-mode": "cors",
"sec-fetch-site": "same-site"
},
"referrer": "http://localhost:3000/",
"referrerPolicy": "strict-origin-when-cross-origin",
"body": "{\"pauri\":[{\"line_number\":1,\"content_unicode\":\"ਆਪ ਅਛਤ ਸਮਰੱਥ ਪ੍ਰਭੁ ਦਈ ਬਡਾਈ ਨਾਮ ।\",\"content_gs\":\"Awp ACq smr`Q pRBu deI bfweI nwm [\",\"content_transliteration_english\":\"aap achhat samara'th prabh dhiee baddaiee naam |\",\"first_letters\":\"ਆਅਸਪਦਬਨ\",\"thamkis\":[],\"vishraams\":[]}],\"last_pauri_id\":60}",
"method": "POST",
"mode": "cors",
"credentials": "omit"
});

Send nested json data with get method using axios

I am trying to send a nested json data with get method using axios, but the problem is that the backend considers the children as a string.
const TOKEN = "token"
const config = {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': TOKEN,
},
data: {},
params: {
"page_id": 1,
"filter": {
"search": "name"
}
}
};
axios.get("http://localhost/api/pages", config)
What I get if I want to print filter in backend:
"{"search": "name"}"
You may have two options:
1- The first option is to decode the string you receive to json.
e.g.
---json_decode() in php
--- JSONObject() in java
--- JSON.parse() in nodejs
or any other method depending on your backend language...
2- The second option is to send your object in this format:
params: {
"page_id": 1,
"filter[search]": "name"
}
And pay attention not to put search in quotes!
You can use req.query on the server side:
function get(req, res, next) {
const { filter } = req.query;
console.log(filter);
...
}
Do a JSON.parse() of your Request.query.filter. Note that Request should be the request variable in your backend.

Can't fetch data on php server, via javascript; [duplicate]

I tried a ReactJS fetch call to a REST-API and want to handle the response. The call works, i get a response, which i can see in Chrome Dev Tools:
function getAllCourses() {
fetch('http://localhost:8080/course', {
method: 'POST',
mode: 'no-cors',
credentials: 'same-origin',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
objectClass: 'course',
crud: '2'
})
}).then(function (response) {
console.log(response);
return response.json();
}).catch(function (err) {
console.log(err)
});
}
When i try to handle the response, i got a "SyntaxError: Unexpected end of input" at
return response.json();
The console.log looks like this:
My Response JSON looks like this, it is valid, i checked it with jsonlint:
[
{
"0x1": {
"users": [],
"lectures": [],
"owner": "0x2",
"title": "WWI 14 SEA",
"description": null,
"objectClass": "course",
"id": "course_00001"
},
"0x2": {
"username": "system",
"lectures": [],
"course": null,
"solutions": [],
"exercises": [],
"roles": [
"0x3",
"0x4",
"0x5"
],
"objectClass": "user",
"id": "user_00001"
},
"0x3": {
"roleName": "ROLE_ADMIN",
"objectClass": "role",
"id": "role_00001"
},
"0x4": {
"roleName": "ROLE_STUDENT",
"objectClass": "role",
"id": "role_00002"
},
"0x5": {
"roleName": "ROLE_DOCENT",
"objectClass": "role",
"id": "role_00003"
}
}
]
You need to remove the mode: 'no-cors' setting from your request. Setting no-cors mode is exactly the cause of the problem you’re having.
A no-cors request makes the response type opaque. The log snippet in the question shows that. Opaque means your frontend JavaScript code can’t see the response body or headers.
https://developer.mozilla.org/en-US/docs/Web/API/Request/mode explains:
no-cors — JavaScript may not access any properties of the resulting Response
So the effect of setting no-cors mode is essentially to tell browsers, “Don’t let frontend JavaScript code access the response body or headers under any circumstances.”
People sometimes try setting no-cors mode when a response doesn’t include the Access-Control-Allow-Origin response header or else because the request is one that triggers a CORS preflight, and so your browser does an OPTIONS preflight.
But using no-cors mode isn’t a solution to those problems. The solution is either to:
configure the server to which you’re making the request such that it sends the Access-Control-Allow-Origin response header, and such that it handles OPTIONS requests
or set up a CORS proxy using code from https://github.com/Rob--W/cors-anywhere/ or such; see the How to use a CORS proxy to get around “No Access-Control-Allow-Origin header” problems section of the answer at No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API
In your then you should check if the response is OK before returning response.json:
.then(function (response) {
if (!response.ok) {
return Promise.reject('some reason');
}
return response.json();
})
If you want to have the error message in your rejected promise, you can do something like:
.then(function (response) {
if (!response.ok) {
return response.text().then(result => Promise.reject(new Error(result)));
}
return response.json();
})
I know this answer might be super late and might have been resolved but i just had the same issue today and I just needed to add a ',' at the end of the headers hash and i stopped getting the error
export function addContacts(formData) {
return(dispatch) => {
dispatch({type: 'POSTING_CONTACTS'});
console.log(formData)
return fetch(uri, {
method: 'POST',
body: JSON.stringify({contact: {name: formData.name, phone_number: formData.phoneNumber}}),
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
})
.then(response => {
return response.json()
}).then(responseJSON => {
console.log(responseJSON)
return dispatch({type: 'ADD_CONTACT', payload: responseJSON});
})
}
}
You can avoid the problem with CORS policy by adding in the header of php or another server endpoint the row:
<?php
header('Access-Control-Allow-Origin: *');
//or
header('Access-Control-Allow-Origin: http://example.com');
// Reading JSON POST using PHP
$json = file_get_contents('php://input');
$jsonObj = json_decode($json);
// Use $jsonObj
print_r($jsonObj->message);
...
// End php
?>
Model of working fetch code with POST request is:
const data = {
optPost: 'myAPI',
message: 'We make a research of fetch'
};
const endpoint = 'http://example.com/php/phpGetPost.php';
fetch(endpoint, {
method: 'POST',
body: JSON.stringify(data)
})
.then((resp) => resp.json())
.then(function(response) {
console.info('fetch()', response);
return response;
});
Simply copy the following code and paste it on your web.config file under <system.webServer> tag.
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
</customHeaders>
</httpProtocol>

How to send chat message using skype BOT api

I want to send messages,images ... using skype BOT API. If there is any other NPM available for doing skype chat.
Refer how to get access token from the docs
https://azure.microsoft.com/en-us/documentation/articles/active-directory-v2-protocols-oauth-code/
Then using this token i will try to send message using the following request
Refer docs:
https://docs.botframework.com/en-us/skype/chat/#navtitle
conversationId: 29:f2ca6a4a-93bd-434a-9ca5-5f81f8f9b455
request({
url: 'https://api.skype.com/v3/conversations/29:f2ca6a4a-93bd-434a-9ca5-5f81f8f9b455/activities',
method: "POST",
json: true,
headers: {
Authorization: ' Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6IjIifQ.eyJpYXQiOjE0NzMzMTk4MDEsImV4cCI6MTQ3MzQwNjqwqwqwqwt5cGVpZCI6ImFtdF8wNjIiLCJzY3AiOjk1OCwiY3NpIjoiMCIsImNpZCI6ImVhODhhYWFmMmFkMjYwYzEiLCJhYXQiOjE0NzMzMTk4MDF9.ZrC0weALCz7QbUHFslJZD7L16k_ciFSCNY-q29h99x70qNrpB5e71KYrD18FTZ-3tI8Ck37_91yMHleQZvEziyEq5-t9EOaGM32RiF0iwnKZcbkOkvgqofWmcGdPT63HEyjWBHg3e_NLIE-RnDob4vMCQrHTkqmuQq6cVaIDkjke1Yi4xjONUNIB9QpWmpuRju0Kxi7oIJqiHWQK',
'Content-Type': 'application/json'
},
body: {
"type": "message/text",
"text": "Hi! (wave)"
}
}
But got error:
{ status: { code: 40499, text: 'No handler found for resource' } }
How to get conversationId?
You are addressing different domain. url should be https://apis.skype.com/v3....

Categories