POST request not registering

235 Views Asked by At

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.

1

There are 1 best solutions below

0
bh013 On

First of all, always send headers before includes
or send all of headers in top of first include file


Removing first if may solve your problem

if( $_SERVER['REQUEST_METHOD'] == 'POST' ) {

Also this may help you to check $_SERVER contents

die( print_r( $_SERVER ) );