Don't get text back from HTTP fetch request with status 200 - php

I'm new to react and try to send a request to my local apache server (run via xampp).
fetch('http://localhost:80', {
method: 'POST',
headers: {'Accept': 'text/*'}
}).then(
(response) => {response.text();}
).then(
(msg) => {console.log(msg)}
).then(
(error) => {console.log(error)}
);
The response returns the status code 200. The php script writes to a text file and echos Hello World.
<?php
header('Access-Control-Allow-Origin: http://localhost:3000');
$FILE = fopen("test.txt", "w");
fwrite($FILE, "Hello World");
?>
Hello World!
After executing the fetch, the console contains [undefined] twice. I previously logged the response, which contains an empty text attribute (and an empty json attribute), as well as status code 200 (Success). Also, the text-file is created, so the php-script definitely runs.
How can I see Hello World?

you have to return response from the response.text() section..
}).then(
(response) => { return response.text();}
).
or simply
}).then(
(response) => response.text();
).
and also in error section use .catch instead of .then

Related

Getting 409 error when calling php from my React application

I am trying to call a simple php file from my React application which will send an email with the details from a contact form. For some reason when the React code executes the fetch of the PHP file, it returns a 409. However, if I manually post the URL into another tab it works as expected, and subsequent calls from my React application then work as expected!
This is my React code:
var url = '/backend/sendmail.php?subject=New Website Enquiry&to=info#site.co.uk&msg=' + msg
console.log(url)
console.log('sending')
fetch(url,
{
'headers': {
'Accept': 'text/html',
'Content-Type': 'text/html'
},
'method': 'GET',
})
.then(
(result) => {
console.log(result.status)
if (result.status === 200) {
console.log('success')
this.togglePop();
this.setState({
name: "",
email: "",
phone: "",
message: "",
terms: false,
})
} else {
console.log('failed')
this.setState({ openError: true })
}
},
(error) => {
console.log('ERROR')
console.log(error)
this.setState({ openError: true })
}
)
And this is my PHP file:
<?php
//header("Access-Control-Allow-Origin: *");
header('Content-Type: text/html');
// error handler function
function customError($errno, $errstr) {
error_log($errstr);
http_response_code(500);
}
// set error handler
set_error_handler("customError");
http_response_code(200);
// send email
mail($_GET["to"],$_GET["subject"],$_GET["msg"],"From: donot.reply#site.co.uk","-f donot.reply#site.co.uk");
error_log($_GET["subject"].":\n".$_GET["msg"], 0);
echo 'OK';
?>
I have spent several days trying to figure out why this is happening. My htaccess file seems OK as once I have made one succesful call to the PHP file it works after that!
It's not a CORS issue as the file is on the same domain.
Anyone got any ideas?
You are sending the wrong request to the server, and that's why you get a 409 error. You should encode the URL params before sending a request
const url = '/backend/sendmail.php?subject=New Website Enquiry&to=info#site.co.uk&msg=' + msg;
const encoded = encodeURI(url);
console.log(encoded)
// expected correct URI: "/backend/sendmail.php?subject=New%20Website%20Enquiry&to=info#site.co.uk&msg="
You can read more about it here

why did nodejs request POST giving 400 status code and not posting data

I'm trying to make a post request to my php code to get some data posted from nodejs but when i try to access the php file it works fine but in nodejs output it gives error to me and not posting data.
My nodejs
const request = require('request');
const notification_options = {
url: 'https://my-site.com/site/push',
json: true,
body: {
var1:"test1",
var2:"test2"
}
};
request.post(notification_options, (err, res, body) => {
if (err) {
return console.log(err);
}
console.log(`Status: ${res.statusCode}`);
console.log(body);
});
PHP Code (https://my-site.com/site/push) :
public function actionPush(){
var_dump($_POST);
}
Output :
Status code : 400
when I access my php file directly from my browser it works and it returns an empty array.
How i can solve this, i need data to be posted into my php and there i want to read them.
Thanks

Axios and reactjs showing empty posted data at php backend

Iam using the Axio Reactjs code below to post form data to php backend.
when I check record.php files from the chrome browser console and
network. it shows that connection is okay but posted data is empty. it seems like the axios is not sending the data to php backend.
I have tried some solutions here on SO but cannot get it to work. Any work around will be appreciated.
axios({
method:'POST',
url:'http://localhost/mydata/record.php',
rec:{
myParameter1: 'test',
myParameter2: 'test2',
}
}).then(res => {
const data = res.data;
this.setState({ data });
console.log(data);
})
.catch(err => { // log request error
//this.setState({ error: false });
console.error(err);
})
php code
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: X-Requested-With");
//header("Content-Type: application/json");
//check if file_get_contents is enabled
if( ini_get('allow_url_fopen') ) {
echo "enabled";
} else{
echo "not enabled";
}
$data = file_get_contents("php://input");
$request = json_decode($data);
print_r($request);
print_r($data);
?>
In axios docs you can find data tag:
https://github.com/axios/axios#request-config
// `data` is the data to be sent as the request body
// Only applicable for request methods 'PUT', 'POST', and 'PATCH'
// When no `transformRequest` is set, must be of one of the following types:
// - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
// - Browser only: FormData, File, Blob
// - Node only: Stream, Buffer
data: {
firstName: 'Fred'
},
// syntax alternative to send data into the body
// method post
// only the value is sent, not the key
data: 'Country=Brasil&City=Belo Horizonte',
this is what you need, there is no rec property in axios config
Try removing the key rec in your data segment in axios or better still do something along the lines of
{
rec: {
myParameter1: 'test',
myParameter2: 'test2',
}
}

Unwanted "data" wrapper in PHP response to AngularJS query

I am querying some server with AngularJS using $http.get
var onStuff = function(data) {
console.log( "Stuff received: " + angular.toJson(data));
$scope.stuff = data.data;
};
$http.get("https://some.server.net/stuff")
.then(onStuff, onError);
My back end is written in php and returns a properly formatted JSON.
I checked that loading https://some.server.net/stuff in a browser and testing by command line "php stuff.php" . It looks something like (truncated with ... to fit this screen):
[{"id":"1","user_id":"1","name":"Name1"},
{"id":"2","user_id":"1","name":"Name2"},
...
]
Please note this data is "unwrapped" or "just the array"
However, when onStuff() is invoked my array is "wrapped" inside another data object
Here is the console output
Stuff received:
{"data":[{"id":"1","user_id":"1","name":"Name1"},
{"id":"2","user_id":"1","name":"Name2"},...],
"status":200,
"config":{"method":"GET",
"transformRequest":[null],
"transformResponse":[null],
"url":"https://some.server.net/stuff",
"headers":{"Accept":"application/json, text/plain, */*"}},
"statusText":"OK"}
Here is the php stuff
<?
header('content-type: application/json; charset=utf-8');
header("access-control-allow-origin: *");
require_once("stuff.class.php");
$mysqli = new mysqli( "localhost", "user", "password", "database");
$list = Stuff::getList( $mysqli);
echo json_encode( $list);
$mysqli->close();
?>
I have been following a tutorial using github api, the JSON response was available directly in data
I am pretty sure this has to do with HTTP headers, but I hoped content-type would take care of it
What should I do to remove the unwanted "data" wrapper?
Instead of using the generic promise API (which seems to return an object with everything inside), use the success and error methods provided by $http:
var onStuff = function(data) {
console.log( "Stuff received: " + angular.toJson(data));
$scope.stuff = data.data;
};
$http.get("https://some.server.net/stuff")
.success(onStuff).error(onError);
That should gives you the data in the format you expect. The full API is as follow:
$http({method: 'GET', url: '/someUrl'}).
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
It seems like you expect onStuff to receive only the deserialized JSON data, but that's not what the API does. The object passed to your $http.get(...).then() callback (i.e. onStuff) is a response object with five properties: data, status, headers, config, and statusText--which is exactly what you're seeing in your console output. The data property has the deserialized JSON data, which is why you have to do $scope.stuff = data.data.
If you want onStuff to receive only the deserialized JSON data, you'll have to call it through an intermediary:
$http.get("https://example.com/stuff")
.then( function(response) {
onStuff(response.data);
} );

PHP json_encode data returned to AJAX call goes to fail and not done

Scenario: I have a php script which outputs data in json_encoded array, and an index html page with javascript which calls the php script via AJAX and handles the results.
Problem: AJAX call goes to .fail instead of .done even though it's getting a 200 response code and the responseText is json_encoded array.
After struggling with this I'm looking to you for help, not flames and unwarranted downvotes; I've researched this but the similar questions haven't resolved the issue.
getDomains.php:
<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
$domains = array();
$domains[] = array('domainID' => 1, 'domainName' => 'alpha.com');
$domains[] = array('domainID' => 2, 'domainName' => 'beta.com');
echo json_encode($domains);
?>
getDomains.php output in browser:
[{"domainID":"1","domainName":"alpha.com"},{"domainID":"2","domainName":"beta.com"}]
index.html/ajax.js:
<script>
// Ajax execute
var go = $.ajax({
url: 'getDomains.php',
type: 'POST',
dataType: 'json'
})
.done(function(results) {
console.debug('callAPI done');
console.debug(results);
})
.fail(function(msg) {
console.debug('callAPI fail');
console.debug(msg);
})
.always(function() {
});
</script>
When I visit index.html I see callAPI fail message in console.log.
callAPI fail
Object { ...
responseText: "[{"domainID":"1","domainName":"alpha.com"},{"domainID":"2","domainName":"beta.com"}]"
status: 200
statusText: "OK"

Categories