Error in activecampaign api while creating or updating contact - javascript

I am trying to create a contact using "create or update api" from here: https://developers.activecampaign.com/reference#create-or-update-contact-new
I tried calling the cURL command which gives a proper response but while doing it from axios it gives error.
API: https://deskera4783.api-us1.com/api/3/contact/sync
Method: POST
Code:
var axios = require("axios");
var data = ({
contact: {
email: "jondoe#example.com",
firstName: "John",
lastName: "Doe",
phone: "7223224241",
fieldValues: [
{ field: "1", value: "The Value for First Field" },
{ field: "6", value: "2008-01-20" },
],
},
});
var config = {
method: "post",
url: "https://deskera4783.api-us1.com/api/3/contact/sync",
headers: {
"Api-Token":
"XXX",
"Content-Type": "application/json",
Cookie:
"cmp800513081=0c7070adc5cdc923a8922c47e98dbe77; PHPSESSID=d3e534f9b1a3f61316cd2cf89b41f164; em_acp_globalauth_cookie=caea42ae-d440-4491-9c08-d920b3378638",
},
data,
};
axios(config)
.then(function (response) {
console.log(JSON.stringify(response.data));
})
.catch(function (error) {
console.log(error);
});
Also, in the network tab request params are not seen neither the response is received.
Console error is:
enter image description here

Related

Get data from Google Ads API using App Script

I wanna get out campaigns reports using Google Rest API and it does'nt work in Google ads Apps script.
My code:
function main() {
const API_VERSION = "12";
const CUSTOMER_ID = "***"; //contais real custommer ID
const DEVELOPER_TOKEN = "***"; //contais real developper ID
const MANAGER_CUSTOMER_ID = "***"; //contais real manager ID
const OAUTH2_ACCESS_TOKEN = ""; //contais real ACCES TOKEN
const data = {
"pageSize": 10000,
"query": "SELECT ad_group_criterion.keyword.text, ad_group_criterion.status FROM ad_group_criterion WHERE ad_group_criterion.type = 'KEYWORD' AND ad_group_criterion.status = 'ENABLED'"
};
const url = `https://googleads.googleapis.com/v${API_VERSION}/customers/${CUSTOMER_ID}/googleAds:search`;
const options = {
method: "POST",
headers: {
"Content-Type": "application/json",
"developer-token": DEVELOPER_TOKEN,
"login-customer-id": MANAGER_CUSTOMER_ID,
"Authorization": `Bearer ${OAUTH2_ACCESS_TOKEN}`
},
body: JSON.stringify(data),
"muteHttpExceptions": true
};
Logger.log(UrlFetchApp.fetch(url, options));
}
Result error:
{
"error": {
"code": 400,
"message": "Request contains an invalid argument.",
"status": "INVALID_ARGUMENT",
"details": [
{
"#type": "type.googleapis.com/google.ads.googleads.v12.errors.GoogleAdsFailure",
"errors": [
{
"errorCode": {
"queryError": "UNEXPECTED_END_OF_QUERY"
},
"message": "Error in query: unexpected end of query."
}
],
"requestId": "zKBR9-dJoG9NWAx3iJea2g"
}
]
}
}
But query is valid https://developers.google.com/google-ads/api/fields/v11/query_validator
enter image description here
Could you plese help?
Thanks
I wanna get out campaigns reports using Google Rest API and it does'nt work. My code and result is above.
Based on the documentation of UrlFetchApp, 'body' is not the correct option for passing in the query. You want 'payload'.
const options = {
method: "POST",
headers: {
"Content-Type": "application/json",
"developer-token": DEVELOPER_TOKEN,
"login-customer-id": MANAGER_CUSTOMER_ID,
"Authorization": `Bearer ${OAUTH2_ACCESS_TOKEN}`
},
payload: JSON.stringify(data),
"muteHttpExceptions": true
};

my api is returning invalid JSON nodejs in post request while fectching

I am sending a post request in my next js app API (API is for updating address)
this is my fetching API code
async function handleSubmit() {
const data = { deliveryAddress, landmark, pincode, district, block, state }
const userID = localStorage.getItem("userID")
for (let item in data) {
let element = data[item];
if (element == "") {
toast.error(`${item} field must be filled`, {
position: "top-center",
autoClose: 3000,
hideProgressBar: false,
closeOnClick: true,
pauseOnHover: true,
draggable: true,
progress: undefined
});
break;
}
}
console.log("above try");
console.log({ "address": JSON.parse(JSON.stringify(data)), "userid": JSON.parse(JSON.stringify( userID)) });
try {
console.log("hello");
let res = await fetch(`${process.env.NEXT_PUBLIC_HOST}/api/updateaddress`, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: [{ "address": JSON.parse(JSON.stringify(data)), "userid": JSON.parse(JSON.stringify(userID)) }]
})
let parsedResponse = await res.json()
console.log("response", parsedResponse);
}
catch (error) {
console.log(error)
}
}
and this code is returning an invalid Json error
this code line body: [{ "address": JSON.parse(JSON.stringify(data)), "userid": JSON.parse(JSON.stringify(userID)) }]
this is what I got when I console.log my response body console.log({ "address": JSON.parse(JSON.stringify(data)), "userid": JSON.parse(JSON.stringify( userID)) });
image of console error and the above-logged coder
Summary
I am getting a invalid JSON error but i think my JSON is correct and nothing wrong with api
I am getting a invalid JSON error
Well, your JSON is invalid…
body: [{ "address": JSON.parse(JSON.stringify(data)), "userid": JSON.parse(JSON.stringify(userID)) }]
That's an array, not JSON. You need to pass JSON to the body property.
Also JSON.parse(JSON.stringify(...)) does nothing useful in this context (since it is useful to deep clone simple objects and you don't mutate the value afterwards) so don't do that.
body: JSON.stringify([{ "address": data, "userid": userID }])
… but a 401 status means Unauthorized.

why Github gist API is throwing 400 error?

I'm trying to use Github Gist API to create a gist. The code is shown below:
var result = {
'a.md':'aaa',
'b.md':'bbb',
}
/*
P.S. I also tried this, but it doesn't work, either
var result = {
'a.md' :{
content: 'aaa',
},
'b.md': {
content: 'bbb',
},
}
*/
$.ajax({
type: "POST",
url: 'https://api.github.com/gists',
headers: {
accept: "application/vnd.github.v3+json",
Authorization: `token ${TOKEN}`,
},
data: {
files: result,
description: 'demo',
public: false,
},
success: (response) => {
console.log(response);
},
});
but I received an error: POST https://api.github.com/gists 400 (Bad Request).
the request is:
{
"message": "Problems parsing JSON",
"documentation_url": "https://developer.github.com/v3/gists/#create-a-gist"
}
And I wonder why and how to fix it.
(This is not English native speaking, so don't mind my grammar mistakes)

Try to execute js script in manifest to ask privatte API with post request

I try to use js script in my jps to test credentials with a personal APi. The idea is to return an error code in the jps if credentials are false. In my computer my js script works fine but when i try to start my jps with this i have an javascript error.
my jps:
onInstall:
- script [*]: https://github.com/user/project/blob/master/script.js
responses:
401:
type: error
message: bad credentials
My js script:
const https = require('https')
var name = "some-name"
var password = "some-password"```
const data = JSON.stringify({
"auth": {
"identity": {
"methods": [
"password"
],
"password": {
"user": {
"domain": {
"id": "default"
},
"name": name,
"password": password
}
}
},
"scope": {
"project": {
"domain": {
"id": "default"
},
"name": "some-name"
}
}
}
})
const options = {
hostname: 'mYapi.com',
port: 443,
path: 'mypath',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': data.length
}
}
var req = https.request(options, (res) => {
console.log(`statusCode: ${res.statusCode}`)
console.log(res.statusCode)
return res.statusCode;
})
req.on('error', (error) => {
console.error(error)
})
req.write(data)
req.end()
I get this error in the console :
ERROR: script.response: {"result":1704,"line":50,"response":null,"source":"hx-core","time":122,"error":"org.mozilla.javascript.EvaluatorException: syntax error"}
And i try a lot of differents script to do this post request ----> works in my computer ( api send result 201 if credentials are good and 401 if not ) , -----> doesn't work in jelastic manifest.
So please can you explain me how i can do a post request with json on my API in Jelastic manifest ( js call script ). I thank you in advance !
The code that is executed by the "script" action runs on the JVM therefore it allows you to connect and use Java libraries.
To implement a POST request and determine the status of the output code, you can use Commons HttpClient.
See below for an example.
type: install
name: HttpClient Post
onInstall:
- script: |
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
var client = new HttpClient();
var name = "some-name";
var password = "some-password";
var requestEntity = new StringRequestEntity(toJSON({
"auth": {
"identity": {
"methods": [
"password"
],
"password": {
"user": {
"domain": {
"id": "default"
},
"name": name,
"password": password
}
}
},
"scope": {
"project": {
"domain": {
"id": "default"
},
"name": "some-name"
}
}
}
}), "application/json", "UTF-8");
var post = new PostMethod("https://example.com/");
post.setRequestEntity(requestEntity);
var status = client.executeMethod(post);
post.releaseConnection();
if (status == HttpStatus.SC_CREATED) { // 201
return { type : "success" };
} else if (status == HttpStatus.SC_UNAUTHORIZED) { // 401
return { type: "error", message: "bad credentials" };
}
return { type: "error", message: "unknown error" };
Also, you can find many useful examples and information in the Jelastic JPS Collection repository.
Perhaps the next script will be useful for you:
https://github.com/jelastic-jps/git-push-deploy/blob/master/scripts/add-web-hook.cs
One last thing that if you don't need the exact HTTP Status, you can use an integrated "Transport" class.
import com.hivext.api.core.utils.Transport;
var name = "some-name";
var password = "some-password";
var data = toJSON({
"auth": {
"identity": {
"methods": [
"password"
],
"password": {
"user": {
"domain": {
"id": "default"
},
"name": name,
"password": password
}
}
},
"scope": {
"project": {
"domain": {
"id": "default"
},
"name": "some-name"
}
}
}
});
try {
new Transport().post("https://example.com/", data, {
'Content-Type': 'application/json',
'Content-Length': data.length
});
return { type: "success" };
} catch (e) {
return {
type: "error",
message: "unknown error: " + e
};
}

Restangular: Uploading multi-part form causes error on send

I'm lost trying to upload a file using restangular.js as part of a multi-part form.
This is the error I get:
XPCWrappedNative_NoHelper { message: "JavaScript component does not have a method named: "available"'JavaScript component does not have a method named: "available"' when calling method: [nsIInputStream::available]", result: 2153185328, name: "NS_ERROR_XPC_JSOBJECT_HAS_NO_FUNCTION_NAMED", filename: "https://ajax.googleapis.com/ajax/libs/angularjs/1.2.17/angular.js", lineNumber: 8407, columnNumber: 0, location: XPCWrappedNative_NoHelper, inner: null, data: null } angular.js:9899
XPCWrappedNative_NoHelper { message: "JavaScript component does not have a method named: "available"'JavaScript component does not have a method named: "available"' when calling method: [nsIInputStream::available]", result: 2153185328, name: "NS_ERROR_XPC_JSOBJECT_HAS_NO_FUNCTION_NAMED", filename: "https://ajax.googleapis.com/ajax/libs/angularjs/1.2.17/angular.js", lineNumber: 8407, columnNumber: 0, location: XPCWrappedNative_NoHelper, inner: null, data: null }
This is my code to send the object:
$rootScope.objects.user.withHttpConfig({
transformRequest: angular.identity
},
}).customPUT($scope.objects.user, "", { // I've tried regular `put` as well
'Content-Type': undefined
}).then(function(resp) {
if (resp == "OK") {
$scope.successes = [{
msg: "Saved"
}];
}
}, function(err) {
console.log(err);
$scope.errors = err.data.errors;
});
The user object contains the following:
{
username: "...",
email: "...",
profilePicture: [File] // What makes this complicated
}

Categories

Resources