Invalid json in request body using ionic push - javascript

Couldn't find what's wrong with my req object. I got this error when trying to send push notification in the callback. Tried to link my request data using jslint.com, nothing wrong with it. Been scratching head for hours for this!
{"link": null, "message": "Invalid JSON in request body. For empty
JSON, pass '{}'.", "type": "UnprocessableEntity"}
my code as below :
var title = req.body.title,
message = req.body.message;
// Define relevant info
var ionic_api_token = 'eyJ0eXAiOTdGb-xQVQaD2sV7qTh7XNKCnwiJKV1QiLJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI2MjiNC03YjE5LTQ3MzMtYjJhMy0zM2Y3MjBkYzU4MjcifQ.s3e6pCwlVUBAs8kvbO';
var device_tokens = ['d44pDarVamnNJS2cNJ2modyBxjZZxcHLlnhQN4wZkJdbgkOw96rq9EEv2WCA5MKU6do0pJoO5rsmQsBAecFt4OIFB0hhD4Dp2K-uMbjum828j-8LKtpCTtGoIDBUvYI6L'];
var ionic_security_profile = 'main';
// Build the request object
var req = {
method: 'POST',
url: 'https://api.ionic.io/push/notifications',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + ionic_api_token
},
data: {
"tokens": device_tokens,
"profile": ionic_security_profile,
"notification": {
"title": title,
"message": message,
"android": {
"title": title,
"message": message
},
"ios": {
"title": title,
"message": message
}
}
}
};
function callback(error, response, body) {
console.log(body)
}
request(req, callback);
});

Only thing that could cause problem are the title & message objects(probably string). Please try escaping it, like below
function escapeJson(json) {
return JSON.parse(JSON.stringify(json));
}
title = escapeJson(title);
message = escapeJson(message);
var req = {
method: 'POST',
url: 'https://api.ionic.io/push/notifications',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + ionic_api_token
},
data: {
"tokens": device_tokens,
"profile": ionic_security_profile,
"notification": {
"title": title,
"message": message,
"android": {
"title": title,
"message": message
},
"ios": {
"title": title,
"message": message
}
}
}
};

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
};

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
};
}

github says cannot parse json while creating a repo in rest api

I'm learning REST api for github and trying to create a new repository by running a JS. Here is my function for creating a new repo: the token is generated, and all access/scopes is granted for my token.
function createNewRepo(userId, name){
var options = {
url: urlRoot + "/user/repos",
method: 'POST',
headers: {
"User-Agent": "EnableIssues",
"content-type": "application/json",
"Authorization": token,
"name": name,
"description": "This is repo creating by REST",
"homepage": "https://github.com",
"private": false,
"has_issues": true,
"has_projects": true,
"has_wiki": true,
}
};
//console.log(eval(options));
request(options, function (error, response, body)
{
var obj = JSON.parse(body);
console.log( obj );
});
}
however when running this, I find,
{ message: 'Problems parsing JSON', documentation_url: 'https://developer.github.com/v3' }
I'm not sure how exactly could the JSON be invalid.
Also, the documentation says it must include public_repo or repo which I'm also not sure how to apply here.
This for me has created the repository.
var myToken = "token INSERTHERETHETOKEN"; // <-- there must be the word token before the actual token.
var urlRoot = "https://api.github.com";
var request = require("request");
function createNewRepo(user, name, token){
var options = {
url: urlRoot + "/user/repos",
method: 'POST',
headers: {
"User-Agent": user,
// "content-type": "application/json", This is set by json:true
"Authorization": token,
"Accept": "application/vnd.github.v3+json"
},
body: {
"name": name,
"description": "This is repo creating by REST",
"homepage": "https://github.com",
"private": false,
"has_issues": true,
"has_projects": true,
"has_wiki": true
},
json: true
};
request(options, function (error, response, body) {
// Do your stuff... but notice that response
// is already a json object and you don't need to parse it.
});
}
createNewRepo("YourGithubUser", "test.repository", myToken);

Upload Image by ajax gives unsupported media type error

I am trying to upload an image to my server using jquery. I need to send image, filename and file url to backend. There for I have added these three fields in "data" (refer code). I am doing it like this(below code) but I am getting error in console saying "unsupported media file" 415. How should I solve it?
posterFile = e.target.files;
selectedPoster = posterFile[0];
uploadPoster() {
var blobPosterFile = selectedPoster;
console.log("U called me?")
var formData = new FormData();
formData.append("fileToUpload", blobPosterFile);
var that = this;
let token;
var settings = {
"async": true,
"crossDomain": true,
"url": "https://www.backend.example.name.com/api/v1/videos/",
"method": "POST",
processData: false,
contentType: false,
"credentials": 'include',
"headers": {
Authorization: "Token " + that.props.token_Reducer.token
},
"data": {
"Title": selectedFile.name,
"File": videoURL,
"Poster": formData
},
success:( response, textStatus, jQxhr )=> {
console.log("poster uploaded")
}
}
$.ajax(settings).done((response) => {
});
}
I am getting error saying "unsupported media type" 415

zombie.js xhr json always fail

I want to use zombie js to test my little node app.
I'm using the mock ressoures with zombie but when i write
body: object
in mock.the xhr always fail because of
Request Failed: parsererror, SyntaxError: Unexpected token o
when i write
body: 'json content'
xhr work well
To test this client js
var xhrGetRiver = $.getJSON("api/1/settings/rivers/fs/")
xhrGetRiver.done(function(json) {
console.log(json);
$.each(json, function(index, fsriver) {
insertFSRiver(fsriver);
});
});
xhrGetRiver.fail(function(jqxhr, textStatus, error) {
var err = textStatus + ', ' + error;
console.log("Request Failed: " + err);
});
I have write this test
var data = [];
var json = {
"id": "test",
"properties": {
"url": "/tmp",
"server": "192.168.9.2",
"port": 22,
"username": "testUser",
"password": "test",
"protocol": "ssh",
"update_rate": "15m",
"includes": "*.docx"
}
};
data.push(json);
this.browser.resources.mock('/api/1/settings/rivers/fs/', {
statusCode: 200,
headers: { 'ContentType': 'application/json' },
body: data // xhr fail
//body: '[ { "id":... ... } ]' // Work well
in app i'am using Express framework and i use res.json the array from library.
res.json seem to stringify my array

Categories

Resources