2

I have a php script where I am using $_SERVER["REQUEST_METHOD"]; right at start of script. I then need to check what is request being sent like 'GET', 'POST' etc. Sharing some of the php script as below.

<?php
try {
  $method_name = $_SERVER["REQUEST_METHOD"];
  if ($_SERVER["REQUEST_METHOD"]) {
   // more code
  }
}
?>

What I trying currently is creating a new server with node as follow.

var http = require('http');
http.createServer(function (req, res) {
 console.log(req.method).
 if(req.method === 'POST') {
   // more code
 }
}).listen(8080);

Currently it is not working as my php script, any idea?

Umair Jameel
  • 1,573
  • 3
  • 29
  • 54

1 Answers1

1

Your node.js code has a syntax error, but you are checking correctly the method. You just have to end the request when you're done via res.end so that the browser knows it got the full response.

var http = require('http');

http.createServer(function (req, res) {
    console.log('Received "' + req.method + '" request!');

    if (req.method === 'POST') {
        res.end('This was a POST request');
        return;
    }

    res.end('This was a GET request');
}).listen(8080);
Marin Bînzari
  • 5,208
  • 2
  • 26
  • 43
  • Okay, Can you also help me find alternatives for $_POST['secret']; $_POST['type']; and $resp->message = "Success"; – Umair Jameel Jul 16 '20 at 13:00
  • Also, can you let me know, how can I pass request method while running this node script from terminal? – Umair Jameel Jul 16 '20 at 13:06
  • @UmairJameel to process POST data it's harder to implement in NodeJS. I would suggest to find a tutorial and find it. Generally I would also recommend using a framework like Express for this. There are also responses on SO on how to process POST data: https://stackoverflow.com/questions/4295782/how-to-process-post-data-in-node-js – Marin Bînzari Jul 16 '20 at 15:29
  • @UmairJameel also for making POST requests from terminal you could use `curl -X POST -d "param1=value1&param2=value2" http://localhost:8080/` – Marin Bînzari Jul 16 '20 at 15:31