Getting 411 Length required from nginx when making a json call - json

Working with a new API -- MemberMouse if anyone cares/knows -- and am stuck on an "411 Length Required" response when making a request. I am successfully making the calls to the API with a php function below:
<?php
$inputParams = "apikey={{key}}&apisecret={{secret}}&";
$inputParams .= "email=ivan#email.com";
$apiCallUrl = "http://www.website.com/wp-content/plugins/membermouse/api/request.php?q=/getMember";
$ch = curl_init($apiCallUrl);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $inputParams);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
curl_close($ch);
echo "RAW Response: ".$result."<br />";
$data = json_decode($result);
echo "<pre>";
var_dump($data);
echo "</pre>";
?>
However I'm building my app in Node.js, and I'm trying to make a comparative call using Node's request library. Here's what I have so far.
var request = require('request');
var options = {
url: 'http://www.website.com/wp-content/plugins/membermouse/api/request.php',
json:true,
multipart: [
{
'content-type': 'application/json',
body: JSON.stringify({
'q': '/getMember',
'apikey': '{{key}}',
'apisecret':'{{secret}}',
'email':'ivan#email.com'
}),
}
],
headers: {
'content-type': 'application/json',
'Connection': 'Keep-Alive',
}
};
function callback(error, response, body) {
console.log(response);
if (!error && response.statusCode == 200) {
console.log(response);
}
}
request.post(options, callback);
And it refuses to make it past nginx with a 411 Length Required Error. Anyone have any idea on what's going on? Thank you.

Gave up after hours of trying, and opted in for node-curl -- though not ideal, as it ties into OS operations, it did provide a nice way to pull the information I need. For anyone who's interested:
var curl = require('node-curl');
var inputParams = "apikey={{}}&apisecret={{}}&email=ivan#email.com";
var apiCallUrl = "http://www.website.com/wp-content/plugins/membermouse/api/request.php?q=/getMember";
var options = {
'POST':1,
'POSTFIELDS':inputParams,
'HEADER':0,
}
curl(apiCallUrl, options, function(error, body) {
console.log(JSON.parse(body.body)['response_data']);
});

Related

Chrome extension not receiving Firebase Cloud Messages

Something really weird is happening with me. Yesterday atfernoon I realized my chrome extension wasn't receiving Firebase Cloud Messages sent by my server. I've tried to create a new Chrome Extension with nothing more than the GCM API and a simple server page with the message sender, but it still not working.
Suddenly it started working again and I received ALL the messages that I sent in that period!! I thought it was a server issue and ok. Today in the morning it was working perfectly. BUT AGAIN, in the afternoon, it stopped! I don't know what to do, I've been using Chrome extension with the GCM API for months and it have never happened before.
My extension:
manifest.json
{
"name": "__MSG_myextension__",
"version": "1.3",
"icons": {
"128": "images/my-icon.png"
},
"permissions": [
"background",
"gcm",
"storage"
],
"background": {
"scripts": ["background.js"]
},
"manifest_version": 2,
"default_locale" : "en"
}
background.js (yes I copied from here)
function registerCallback(registrationId) {
console.log(registrationId);
if (chrome.runtime.lastError) {
console.log(chrome.runtime.lastError);
return;
}
}
var senderIds = ["MY-SENDER-ID"];
chrome.gcm.register(senderIds, registerCallback);
chrome.gcm.onMessage.addListener(function(message) {
console.log(message);
});
My server:
$registration_id = '...';
$key = '...';
$message = '{"collapse_key":"'.time().'","data":{"message":"hello world"},"priority":"high","registration_ids":["'.$registration_id.'"]}';
$headers = array(
'Content-Type: application/json; charset=UTF-8',
'Authorization:key=' . $key );
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://fcm.googleapis.com/fcm/send");
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_ENCODING, 'UTF-8');
curl_setopt($ch, CURLOPT_POSTFIELDS, $message);
$result = curl_exec($ch);
var_dump($result);
As a result from my curl, I'm getting always success.
I'm pretty sure I'm sending the message to the right registration ID.
Can somebody help me??

post request with json data cross domain

I have been reading tutorials for two days and I really cant understand what are my options. I have a machine with HMI that runs web server (I dont know what kind of web server that is). I can acces HMI tags values trought POST request with json data.
The rquest example look like this
$( document ).ready(function() {
var data0 = {"getTags":["Start_dav","CutON","run_rot_actual"],"includeTagMetadata":true};
var json = JSON.stringify(data0 );
$.ajax({
url: "http://ipaddress/tagbatch",
type: "POST",
dataType: "json",
data: json,
The response is json data.
The problem is of course in cross domain policy. I have no control over the machine and there is no option to set up CORS. I have read about proxy, iframe and yql solutions but as I understand I cant send json data with these workarounds. Is there any way how to send post request with json cross domain?
Thank you for you help
I found a solution. I am using php curl for sending a request.
Here is the working code:
$data = array("getTags" => array("Var1","Var2"), "includeTagMetadata" => false);
$data_string = json_encode($data);
$agent= 'Mozilla/5.0 (Windows; U;Windows NT 5.1; ru; rv:1.8.0.9) Gecko/20061206 Firefox/1.5.0.9';
//open connection
$ch = curl_init();
$f = fopen('request.txt', 'w'); //writes headers to this file
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL,"domainipaddress");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch,CURLOPT_POSTFIELDS,$data_string);
$tmpfname = dirname(__FILE__).'/cookie.txt'; //saves the cookie from server
curl_setopt($ch, CURLOPT_COOKIEJAR, $tmpfname);
curl_setopt($ch, CURLOPT_COOKIEFILE, $tmpfname);
curl_setopt($ch, CURLOPT_ENCODING, '');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER , false);
curl_setopt($ch, CURLOPT_USERAGENT, $agent);
curl_setopt( $ch, CURLOPT_AUTOREFERER, true );
curl_setopt( $ch, CURLOPT_VERBOSE, 1 );
curl_setopt( $ch, CURLOPT_STDERR, $f );
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true );
curl_setopt($ch, CURLOPT_FORBID_REUSE, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string),
'Connection: keep-alive',
"Keep-Alive: 300"
)
);
//execute post
$result = curl_exec($ch);
$headers = curl_getinfo($ch);
fclose($f);

Standard Json objects for different push notification services

Is there actually a required json object which each push service requires. For example I always see the following in every tutorial:
Android:
var notification = "{\"data\":{\"msg\":\"Breaking " + category + " News!\"}}";
Apple:
var alert = "{\"aps\":{\"alert\":\"Breaking " + category + " News!\"}}";
Do these structures have to be kept? or can I send my own custom objects down to the phone?
I think your question is quite specific to certain platform you are trying to send the Push Notification. If you want to just implement the GCM on standard Android Native App.. You can just embed the code in your server implementation.
public function send_notification($registatoin_ids, $message) {
// include config
include_once './config.php';
// Set POST variables
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $registatoin_ids,
'data' => $message,
);
$headers = array(
'Authorization: key=' . GOOGLE_API_KEY,
'Content-Type: application/json'
);
// Open connection
$ch = curl_init();
// Set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Disabling SSL Certificate support temporarly
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
// Execute post
$result = curl_exec($ch);
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
}
// Close connection
curl_close($ch);
echo $result;
}
So the answer to your question is No.

Angular $http with bbc radio api

I need to get this json from bbc radio:
http://www.bbc.co.uk/radio1/playlist.json
I can get it from POSTMAN, but then I try to get it from my angular app, I've got an error.
XMLHttpRequest cannot load http://www.bbc.co.uk/radio1/playlist.json. No 'Access-Control-Allow-Origin' header is present on the requested resource
Yes, I saw a lot simular guestions on Stack Overflow, but I think this is not a server task to solve.
In my angular code I've got this:
async: function (radio) {
return $http({
method: 'GET', //or JSON
url: api.url + radio + '/playlist.json',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Access-Control-Allow-Origin': '*'
}
})
.success(function (d) {
console.log('done');
})
.error(function (d) {
console.log('nope');
});
}
And this in config:
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
But CORS isn't working anyway.
Apparently this playlist and BBC api doesn't support jsonp and have no CORS setup so the solution that I can think from top of my head would be to use i.e. CURL
http://plnkr.co/edit/66yErNbEkONrcC8LjqUV?p=preview
$http.jsonp('http://edeen.pl/curl.php?callback=JSON_CALLBACK').then(function(response){
$scope.playlist = response.data
console.log(response.data)
})
curl.php
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.bbc.co.uk/radio1/playlist.json");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);
echo $_GET['callback'].'('.$output.')';

Can't create a Folder using BOX API v2.0

function post($url, $params, $headers) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$parent_id = 0;
$name = 'examplefolder';
$params = array('name' => $name => json_encode(array('id' => $parent_id)));
$resp = post('https://api.box.com/2.0/folders', $params, array('Authorization: Bearer ' . $ACCESS_TOKEN_HERE));
When this code executes I got this error in Json format
{"type":"error","status":400,"code":"bad_request","context_info":{"errors":[{"reason":"missing_parameter","name":"parent","message":"'parent' is required"},{"reason":"missing_parameter","name":"name","message":"'name' is required"}]},"help_url":"http:\/\/developers.box.com\/docs\/#errors","message":"Bad Request","request_id":"204107642652b93aceca050"}
Is there anything I'm missing?
Additional note.
I even tried to make the params a query string like this.
name=examplefolder&parent={"id":0}
and this gives me a different error
{"type":"error","status":400,"code":"bad_request","context_info":{"errors":[{"reason":"invalid_parameter","name":"entity-body","message":"Invalid value 'name=examplefolder&parent={\"id\":0}'. Entity body should be a correctly nested resource attribute name\/value pair"}]},"help_url":"http:\/\/developers.box.com\/docs\/#errors","message":"Bad Request","request_id":"154368831052b93bb027779"}
I'm not totally familiar with this language syntax, but it looks to me like the parent object is not declared in your POST body. You need to be sending this:
{"name":NAME, "parent":{"id":"0"}}
You might be able to accomplish that by changing your $params like so:
$params = array('name' => $name, 'parent' => json_encode(array('id' => $parent_id)));
Also, per the documentation the $parent_id should be serialized as a string, not as an integer.
{"name":NAME, "parent":{"parent_id":"0"}}
This worked for me when I was working Angular 1 - angular file upload module.
However it is different with angular2, still working on..
vm.uploader.onBeforeUploadItem = function (item) {
if (!vm.parentFolderId || item.isVersionUpload) return;
item.headers = { Authorization: 'Bearer ' + vm.userToken };
item.formData = {
name: item.file.name,
parent: {
parent_id: vm.parentFolderId
}
};
}