Issue with fetch PHP not getting POST data - fetch-api

I'm using the following code :-
Javascript :-
var t_sql="SELECT * FROM `compliance_report`;";
const options = {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify( {sql: t_sql} )
};
fetch( 'test3.php', options )
.then( response => response.json() )
.then( response => {
console.log(response);
} );
The PHP code is just to echo back the Post data
:-
<?php
$sql=$_POST['sql'];
$au=json_encode($sql);
echo $au;
?>
But all I am getting back is NULL? can anyone tell me what is wrong. I ultimately want to run the query and echo back the result but the server is reporting the $_POST as empty?

Related

Instagram OEmbed - OAuthException 200 Provide valid app ID

I keep getting the error message:
{message: '(#200) Provide valid app ID', type: 'OAuthException', code: 200,...
I can get the HTTP Get response with curl and by entering the URL, but when trying to use the exact same url in the Javascript SDK, i am getting the error told before.
Following is my JS script.
var pageAccessToken = 'APP_ID|CLIENT_ID';
$(document).ready(function() {
$.ajaxSetup({ cache: true });
$.getScript('https://connect.facebook.net/en_US/sdk.js', function(){
FB.init({
appId : 'APP_ID',
xfbml : true,
version : 'v13.0'
});
FB.getLoginStatus(function(response){
FB.api(
'/instagram_oembed',
'GET',
{"url":"https://graph.facebook.com/v13.0/instagram_oembed?url=INSTAGRAMURL&access_token=" + pageAccessToken},
function(response) {
console.log(response);
InstagramPage.innerHTML = response.html;
}
);
console.log(response);
});
});
});
Any ideas?
My app is live (I can get the correct information from HTTP Get)
EDIT:
As CBroe said i changed my code to the following and it now works.
FB.getLoginStatus(function(response){
FB.api(
'/instagram_oembed',
'GET',
{
"url":"INSTAGRAMURL",
access_token: pageAccessToken
},
function(response) {
console.log(response);
InstagramPage.innerHTML = response.html;
}
);
console.log(response);
});
});
So having both the parameters inside the {} works. I originally tried with 2 {}, which didn't work.
However, CBroe, as can be seen in facebook docs: https://developers.facebook.com/docs/facebook-login/guides/access-tokens
I can use the Client_ID in javascript.
Addition - After i wrote it in PHP (with the PHP SDK for facebook), to resolve having the Client ID readable in JS:
<?php
require_once __DIR__ . '/assets/src/Facebook/autoload.php'; // change path as needed
$fb = new \Facebook\Facebook([
'app_id' => 'APP-ID',
'app_secret' => 'APP-Secret',
'default_graph_version' => 'v13.0'
//'default_access_token' => '{access-token}', // optional
]);
/* PHP SDK v5.0.0 */
/* make the API call */
try {
// Returns a `Facebook\FacebookResponse` object
$response = $fb->get(
'/instagram_oembed?url=INSTAGRAMURL',
'APP-ID|APP-ID_or_Client-ID'
);
} catch(Facebook\Exceptions\FacebookResponseException $e) {
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
$Node = $response->getDecodedBody();
echo <<< EOF
<div class=""InstagramResults">
EOF;
print_r($Node["html"]);
echo <<< EOF
</div>
EOF;
?>
ยดยดยด
You are trying to send a instagram_oembed endpoint URL, to the instagram_oembed endpoint. The url parameter should only be the INSTAGRAMURL.
And if you have to pass a different access token than what the SDK will use internally, then that needs to be passed as an additional parameter to the endpoint.
Note that you should not expose your client_id (actually, the app secret) in publicly available client-side code ever though. Everyone could steal it from there, and would have a valid app access token for your app.

Authentication in header with REST API

I am new to coding and trying to work with my first API in Javascript. I am having some trouble figuring out where to populate an API key and header. It is a POST for sending a small message to an IOT device. The reference is here and the header reference is here.
Here is what I have, but I have replaced my API key with the generic one.
request.open('POST', 'https://dashboard.hologram.io/api/1/devices/messages');
request.setRequestHeader('Content-Type', 'application/json');
request.onreadystatechange = function () {
if (this.readyState === 4) {
console.log('Status:', this.status);
console.log('Headers:', this.getAllResponseHeaders());
console.log('Body:', this.responseText);
}
};
var body = {
'deviceid': [storedDeviceID],
'protocol': 'TCP',
'port': 80,
'data': 'Hello world!',
'base64data': 'SGVsbG8gd29ybGQhCg=='
};
request.send(JSON.stringify(body));
I really appreciate any help. Thank you.
Hologram provides an API Key which you need to encode in base64 format first then you can use it in your program.
So you can go to base64encode or any other conversion website ( you can encode it programmatically as well ) and there you have to enter -
apikey:YOUR_API_KEY
Then encode it into base64 format which will be something like
ABCDEFGHIJKLMNOpQrstUVW==
Copy it, and use it in your program. Below is an example using Javascript Fetch API -
var myHeaders = new Headers();
myHeaders.append("Authorization", "Basic ABCDEFGHIJKLMNOpQrstUVW==");
var requestOptions = {
method: 'GET',
headers: myHeaders,
redirect: 'follow'
};
fetch("https://dashboard.hologram.io/api/1/links/cellular", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));

Guzzle getBody() after request return posted body

I'm using Guzzle 6.3. I'm trying to post a data with a header.
This is my code:
$headers = [
'content-type' => 'application/json',
'Accept' => 'application/json'
];
$request = new Psr7\Request('post', 'product', $headers, json_encode($data));
$res = $this->http->send($request);
$resData = json_decode($res->getBody(), true);
The response body ($resData) is always equal to the posted one ($data).
Thank you.
Try
$resData = json_decode($res->getBody()->getContents(), true);
Otherwise (if it doesn't help) check what your API endpoint returns.

REST call to Microsoft Graph

I have got my access token but I am struggling to see how you then send the request for the data required. In the example Call Microsoft Graph they have:
GET
https://graph.microsoft.com/v1.0/me/messages?$select=subject,from,receivedDateTime&$top=25&$orderby=receivedDateTime%20DESC
Accept: application/json Authorization: Bearer token
But what is the method for parsing the Accept: and the Authorization: to Microsoft Graph?
I have tried as a POST but it says bearer token empty.
$token=$_SESSION['$token'];
$url = 'https://graph.microsoft.com/v1.0/me/calendarview?startdatetime=2018-02-08T18:29:54.171Z&enddatetime=2018-02-15T18:29:54.171Z';
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $url,
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => array(
Authorization => 'Bearer ' . $token,
Content-Type => 'application/json'
)
)
);
$resp = curl_exec($curl);
curl_close($curl);
Use the provided graphServiceClient
// Create Microsoft Graph client.
try
{
graphClient = new GraphServiceClient(
"https://graph.microsoft.com/v1.0",
new DelegateAuthenticationProvider(
async (requestMessage) =>
{
var token = await GetTokenForUserAsync();
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", token);
}));
return graphClient;
}
Use that to authenticate your request.
$request = 'https://graph.microsoft.com/v1.0/me/calendarview?startdatetime=2018-02-08T18:29:54.171Z&enddatetime=2018-02-15T18:29:54.171Z';
hrm = new HttpRequestMessage(HttpMethod.Get, request);
// Authenticate (add access token) our HttpRequestMessage
await graphClient.AuthenticationProvider.AuthenticateRequestAsync(hrm);
// Send the request and get the response.
response = await graphClient.HttpProvider.SendAsync(hrm);
jsonString = await response.Content.ReadAsStringAsync();

axios post server does not receive data from browser

I am using axios.post but the server does not seem to receive the post-data.
This is what I have:
var baseURL = "http://localhost:8888/dbRouting.php";
var body = {
function: 'foo',
id: 'bar',
}
axios.post(baseURL, body)
.then((response) => { console.log( "Data Loaded AXIOS: " + response.data ); })
.catch(function (error) {console.log(error);});
// Data Loaded AXIOS: array(0) {
// }
This jQuery post to the same file, on the other hand, works:
$.post( baseURL, body )
.done(function( data ) {
console.log( "Data Loaded JQUERY: " + data );
});
//Data Loaded JQUERY: array(2) {
//["function"]=>
//string(3) "foo"
//["id"]=>
//string(3) "bar"
//}
The server file (dbRouting.php) is just:
<?php
var_dump($_POST);
?>
Any ideas what might be going on?
This is my way of allowing the back-end which is php to process it via $_POST. This is part of my code in vue inside method section.
Assuming you are post it to a post_url and you have an object, var myObject:
var myObject = {
property: value,
property1: value1,
property2: value2
}
Inside my vue, method section:
updateForm: function( myObject ){
var post_url = (your post url);
axios.post(post_url, makePostReady( myObject ) )
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
}
Then above(before axios post call) or make it a global function. I created below function to turn any object I want to send as post using axios so that it will form
property=value&poperty1=value1&property2=value2......
Below is the function:
function makePostReady( object )
{
var sentence = "";
for (var key in object) {
sentenceAdd = key + '=' + object[key] + '&';
sentence = sentence + sentenceAdd;
}
//console.log( 'sentence: ' + sentence );
return sentence;
}
After that you can var_dump( $_POST ) at your post_url to check if everything is fine. Then you can process the data as usual.
Hopefully it helps
Below is some picture to help understanding better
It seems a networking issue.
Double check the URL and the port localhost:8888/dbRouting.php on JQuery & Axios demo
Are they exactly the same?
Is your .catch fired on axios? What's the error?
is your server responding on localhost:8888?
Alternatively, you can check your server implementation using a different client (e.g. Postman https://chrome.google.com/webstore/detail/postman/fhbjgbiflinjbdggehcddcbncdddomop?hl=en)