0

I m trying to communicate between PHP laravel and Node js.

  $ch = curl_init();

curl_setopt($ch, CURLOPT_URL, 'http://mylocalip/publish');

curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_PORT, 8001);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($ch, CURLOPT_POST, true);
$pf = array('clientId' => '123123', 'command' => '{"cmd":"start"}');
curl_setopt($ch, CURLOPT_POSTFIELDS, $pf);
curl_exec($ch);
curl_close($ch);
    dd("Done");

This is what m using in php to send data, As it is sending data but on node m not getting any response, tried in angular it is responding as expected but on php side it isn't responding.

var express = require("express");
var app = express();
    app.post("/publish", function(req, res) {

    console.log(req, res);
    console.log(req.body);
    });
});

i want to get data in console that im sending from php. Is it possible that both laravel and node is currently running on localhost with different ports that's why it is not responding. If yes then how do angular is able to send data to node. Thank you,

2 Answers 2

3

On the PHP side, set the CURLOPT_HTTPHEADER to something like curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);

If you're using the json content-type, ensure the post data is json encoded:

curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post_data));

In the NodeJS script, if you are using express 4.16+, you can use the inbuilt body-parser middleware:

app.use(express.json()) OR app.use(express.urlencoded()) in order for express to attach the data from your PHP to the request body.

Full example:

const app = require('express');

//depending on the content type you set in your PHP
app.use(express.json());
app.use(express.urlencoded());

app.post('publish', (req, res)=>{
  console.log(req.body);
})

Sign up to request clarification or add additional context in comments.

Comments

0

We use a traditional Linux host with Apache, PHP and MySQL. ... Both PHP and Node.js can get admission to the equal MySQL database, so the whole communication between PHP and Node.js can be handled at the database level. If it truly is no longer enough, you can always use a cache server such as Memcached or Redis.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.