I've took some code from other posts to implement Apache app to request Node app.
Following Node app "works" but I cannot access post parameters which are undefined.
//NODE
express = require('express');
bodyParser = require('body-parser');
app = express();
port = 3000;
app.use(bodyParser.json());
app.post('/get_php_data', function (req, res) {
// php array will be here in this variable
var data = req.param.data; // I've tried req.body.data;
var response = String(data)+String((7*data+3*data+1*data) % 3);
console.log(req); // This seems log req parameter in a loop
res.send(data);
});
app.listen(port);
PHP-part (just POST request with one parameter):
echo httpPost('localhost:3000/get_php_data', array('data' => 1));
function httpPost($url,$params)
{
$postData = http_build_query($params);
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch,CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_POST, count($postData));
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
$output=curl_exec($ch);
curl_close($ch);
return $output;
}
This setup returns undefined. How to access POST parameters with Node?
Well, answer was simple. In Node script change the 5th line as follows:
//app.use(bodyParser.json());
app.use(bodyParser());
You don't have to run server if they are on same machine you can use php `` which interprets commands line. No need to run http on same machine to reach it.
Related
I'm setting up a new notification server with nodejs and socket.io. The server it is working, with postman I can send a POST request and indeed sends the notification but with PHP it's taking for ages to send the POST with curl and it's not really working
The nodejs server is running on debian 9, I got a SSL certificate from let's encrypt so it's authenticated, like I said before with postman ( https://www.getpostman.com/ ) I can make the POST request and works. I'm sending headers with a secret key and body with data to the notification
#!/usr/bin/env node
var fs = require('fs');
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const port = process.env.PORT || 49152;
const notificationSecret = process.env.NOTIFICATION_SECRET;
var server;
if(process.env.SSL_KEY && process.env.SSL_CERT) {
var options = {
key: fs.readFileSync(process.env.SSL_KEY_PATH),
cert: fs.readFileSync(process.env.SSL_CERT_PATH)
};
server = require('https').createServer(options, app);
} else {
console.log("Error creating the server, missing KEY OR CERT");
}
const io = require('socket.io')(server);
server.listen(port, () => console.log('Server listening at port %d', port));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(express.static(__dirname + '/public'));
app.post('/send', (req, res) => {
... more but not important
and PHP
$data = array("notification" => "IF THIS WORKS", "channel" => "myChannel");
$payload = json_encode($data);
// Prepare new cURL resource
$ch = curl_init('IP/send');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
// Set HTTP Header for POST request
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'notification_secret: ')
);
// Submit the POST request
$result = curl_exec($ch);
// Close cURL session handle
curl_close($ch);
Anyone has any idea what can I try to fix it?
Hello I am trying to connect from my site with curl (php) to a rest api (node js-express-js) i have made. Everythink seems to work fine except the answer from curl is empty
server from node-js:
var express = require('express'); // call express
var app = express(); // define our app using express
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var port = process.env.PORT || 8080; // set our port
// ROUTES FOR OUR API
// =============================================================================
var router = express.Router();
router.get('/', function(req, res) {
res.json({ message: 'hooray! welcome to our api!' });
});
app.use('/api', router);
app.listen(port);
console.log('Listening on ' + port);
On my site i am trying to retrieve the json by using curl:
<?php
$ch = curl_init();
// set url
curl_setopt($ch, CURLOPT_URL, "xxx:8080/api/"); // i removed the ip from my server for safety reasons
//return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// $output contains the output string
$output = curl_exec($ch);
print "output=";
print_r($ouput);
// close curl resource to free up system resources
curl_close($ch);
?>
Note: sending a get request above from postman i receive the answer i want. I don't know what is wrong. Thx in advance.
Also, curl is a blocking function.. right?
Both "servers" are on the same server. I don't know if is an error like cross-server-origin of javascript
reason why you don't get response via php - wrong var name in print_r func
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "xxx:8080/api/");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
print "output=";
print_r($output); // missed t in output
curl_close($ch);
?>
Is there a way to send any kind of request from the PHP script to the Node.js script?
For example I have this directory:
scripts
|_sender.php
|_receiver.js
I want to send some data from php script and read it with node.js script to execute some action.
How is this done properly?
The easiest way I use is to pass your PHP data to node using HTTP post or get, here is my code to send data from PHP to the node.
// Node Side
var express = require('express');
express = express();
var bodyParser = require('body-parser');
express.use(bodyParser.json());
express.post('/get_php_data', function (req, res) {
// php array will be here in this variable
var data = req.body.data;
res.send(' Done ');
});
// PHP Side
httpPost('NODE_URL:2200/get_php_data', array('data' => 'some data'));
function httpPost($url,$params)
{
$postData = http_build_query($params);
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch,CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_POST, count($postData));
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
$output=curl_exec($ch);
curl_close($ch);
return $output;
}
It depends where js will read it incoming data
If it is a server, start it with node receiver.js then send from your php to http://local host/.... Whatever your server is listening on
Or you can dump your php output into a file and read it by the receiver after
You should provide more informations to get a better answer
i wrote a script, that should call a simple soap service (in python) to receive datas. The url requires get parameters, to work fine.
I realized the request with php curl:
<?php
// Curl Init
$ch = $curlObject;
// Set URL
$url = "http://localhost/soapService/?";
// Add get params
$url .= http_build_query(array("article" => "[($articleNR, 5)]"));
// Fill curl
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Execute
$serverOutput = curl_exec($ch);
?>
But the response says:
"NameError: name 'article' is not defined"
And if i call the URL directly in my browser, everything works fine. Where is the magic?
Ah, just made it! There was a missing CURL PARAM
curl_setopt($ch, CURLOPT_HTTPGET, true); // Now everything works fine!
Im trying to send a GET or POST request from PHP (CLI), to a Node.js/Sockets.IO application, using only basic cURL. This is what i have so far, i can see the response coming in to node.js (from the cli), but can not get any farther. Currently i only want the parameters sent to the console. (I can expand on that later)
Any help would be great!
(FYI: I did look at this, Socket.io from php source, but need more help. Exact code would be great)
PHP
$qry_str = "?msg_from_php=This_is_a_test123&y=20";
$ServerAddress = 'http://10.1.1.69/socket.io/1/websocket/TICWI50sbew59XRE-O';
$ServerPort = '4000';
$TimeOut = 20;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $ServerAddress. $qry_str);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:'));
curl_setopt($ch, CURLOPT_PORT, $ServerPort);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $TimeOut);
curl_setopt($ch, CURLOPT_TIMEOUT, '3');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, true);
// not sure if it should be in an array
//$data = array('msg_from_php' => 'simple message!');
//curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$content = trim(curl_exec($ch));
curl_close($ch);
echo " Sent! Content: $content \r\n";
Node.JS
var express = require('express'), http = require('http');
var app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server);
io.configure('production', function(){
io.enable('browser client minification');
io.enable('browser client etag');
io.enable('browser client gzip');
io.set('log level', 1);
io.set('transports', ['websocket', 'flashsocket', 'htmlfile', 'xhr-polling', 'jsonp-polling']);
io.set("polling duration", 30);
});
server.listen(4000); // 80,443, 843, 4000, 4001
io.sockets.on('connection', function (socket) {
socket.on('msg_from_php, function (data) {
console.log(data);
});
});
You're trying to make an ordinary HTTP connection to a socket.io server, but socket.io doesn't speak plain HTTP; it uses at the very least a specialized handshaking protocol, and if it uses websocket transport it won't be using HTTP at all. AFAIK there's no PHP implementation of a socket.io client.
Fortunately, it looks like your PHP application needs to send to your node application on its own terms, not the other way around, so all you need to do is use express to define a couple routes to implement a RESTful interface; your PHP app can then use cURL to POST to the URL corresponding to the appropriate route.