I am making a post request from a node application to a php file and for some reason the POST request isn't registering. Here is the PHP file:
<?php
include_once('yodafunctions.php');
header('content-type: application/json; charset=utf-8');
header("access-control-allow-origin: *");
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$res = array();
$data = isset($_POST['message']);
if($data) {
$res['message'] = $data;
} else {
$res['message'] = 'well that did not work';
}
echo json_encode($res);
} else {
$test = array('message' => 'post not being sent for some reason');
echo json_encode($test);
}
I'm using npm-request for doing the http request, here is my relevant nodejs server code:
app.get('/', (req, res) => {
console.log(req.query.message);
console.log(req.query);
if(req.query.message && req.query.message !== '') {
console.log(req.query.message);
request({
method: 'POST',
headers: {
'Content-type': 'application/json'
},
followAllRedirects: true,
uri: 'http://localhost/yoda',
json: {
message: req.query.message
}
}, (error, res, body) => {
if(error) {
console.error(error);
return;
}
console.log(`statusCode: ${res.statusCode}`)
console.log(res.body);
})
}
});
The output in the terminal from my last 2 console.log() calls shows:
"statusCode: 200" and
"{ message: 'post not being sent for some reason' }".
So, it looks like the POST request isn't being recognized in the PHP file maybe?
I'm just learning node so I really appreciate the help.
First of all, always send
headers beforeincludesor send all of headers in top of first include file
Removing first
ifmay solve your problemAlso this may help you to check
$_SERVERcontents