I am writing an application with node and laravel. I am running small laravel local server which resolves to http://localhost:8000. i am also running a node server on localhost:3000. Then trying to call the first server from the second. Here is the NodeJs code:
var restify = require('restify');
var server = restify.createServer();
server.listen(3000, function() {
console.log('%s listening at %s', server.name, server.url);
});
Here is where I make the http request:
var http = require('http');
module.exports = {
call: function (host, path) {
var options = {
host: host,
path: path,
port: 8000,
method: 'GET'
};
callback = function(response) {
var str = '';
response.on('data', function (chunk) {
str += chunk;
});
response.on('end', function () {
return str;
});
}
http.request(options, callback).end();
}
}
This is the actual call I am making:
httpCaller.call('http://localhost', '/fire');
I get the following response on the command line:
Error: getaddrinfo ENOTFOUND http://localhost http://localhost:8000
at errnoException (dns.js:26:10)
at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:77:26)
I tried removing http:// and just calling local host, and got the following:
Error: connect ECONNREFUSED 127.0.0.1:8000
at Object.exports._errnoException (util.js:890:11)
at exports._exceptionWithHostPort (util.js:913:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1057:14)
How can I do this?
Try using the http.get function?
http.get('http://localhost:8000/fire', (res) => {
console.log(`Got response: ${res.statusCode}`);
// consume response body
res.resume();
}).on('error', (e) => {
console.log(`Got error: ${e.message}`);
});
Related
I'm developping a PHP website using the Yii2 Framework and I'm trying to implement a socket.io service.
To execute socket.io I use PM2 and my file looks like this :
const { fstat } = require('fs');
var socket = require('socket.io'),
express = require('express'),
https = require('https');
fs = require('fs');
const credentials = {
key: fs.readFileSync('../../../ssl/keys/<path_to_cert_key.key>').toString(),
cert: fs.readFileSync('../../../ssl/certs/<path_to_cert.crt>').toString(),
}
var app = express();
var server = https.createServer(credentials, app);
var io = socket(server, {
cors: {
origin: '<origin_url>',
methods: ['POST', 'GET'],
credentials: true
},
allowEIO3: true,
secure: true
});
io.sockets.on('connection', function(client){
console.log('ok');
client.on('test', function(data){
console.log('test');
console.log(data);
io.sockets.emit('test_r', {message: 'ok'});
});
});
server.listen(30064);
It runs without any error:
pm2 start _socket.js
I can easily access this socket from a view by registering javascript :
var socket = io.connect('<socket_url:port>', {
withCredentials: false,
});
socket.on('test_r', function( data ) {
console.log('it works');
});
It works well if I connect to the socket and emit from a view.
But the thing is that I want to emit an event from a PHP Controller or from a CoreBootstrap Object in a php function like this :
$emitter = new \SocketIO\Emitter( array( 'port' => '30064', 'host' => '127.0.0.1') );
$emitter->broadcast->emit( 'test', ['message' => 'test_message'] );
The module I'm using is ashiina/socket.io-emitter (I also tried a bunch of ohters but they did not work as well).
Nothing happens when I do this. Nothing even happens when I look at the PM2 logs.
Would someone know why the event is not emitted or if there is another way to do it ?
Thanks in advance for your answers.
I am tried to use socket io on the live server and I got this error.
polling-xhr.js:264 GET http://sub.domain.com:3000/socket.io/?EIO=3&transport=polling&t=MFUVMS5 net::ERR_TIMED_OUT
But on my local server, the files worked perfectly. I am working with socket.io and PHP.
Here are my codes:
server.js
var socket = require('./node_modules/socket.io');
var express = require('./node_modules/express');
var app = express();
var server = require('http').createServer(app);
var io = socket.listen(server);
var port = process.env.PORT || 3000;
// server active console view
server.listen(port, function () {
console.log('Server listening at port %d', port);
});
io.on('connection', function (socket) {
// show new added online user
socket.on('now_online', function (data) {
io.sockets.emit('now_online',{
id: data.id,
name: data.name
});
});
});
main.js
var socket = io.connect('http://'+window.location.hostname+':3000');
socket.on('new_online_user', function (data) {
if (login_id != data.online_user) {
$('#contacts-list .contact[data-chat='+data.online_user+']'+' .contact-status').addClass('online');
}
});
package.json
{
"private": true,
"dependencies": {
"gulp": "^3.9.1",
"express": "^4.16.2",
"socket.io": "^2.0.4"
}
}
I was searching in google and StackOverflow about this issue but those solved didn't work for me.
Thanks so much.
Try connecting using only domain without http like:
var socket = io.connect(window.location.hostname+':3000', {transports: ["websocket", "xhr-polling", "htmlfile", "jsonp-polling"]});
It will automatically become ws://sub.domain.com:3000/socket.io/?EIO=3&transport=polling&t=MFUVMS5. I'm using similar to this and working fine.
I am new to socketIO and elephantIO and am trying to emit to a node server from a php file emit_test.php as bellow
ini_set("display_errors",5);
include ("vendor/autoload.php");
use ElephantIO\Client;
use ElephantIO\Engine\SocketIO\Version1X;
$version = new Version1X("http://localhost:3001");
$client = new Client($version);
$client->initialize();
$client->emit("new_order", ["test"=>"test", "test1"=>"test1"]);
$client->close();
server.js file
var socket = require('socket.io');
var express = require('express');
var https = require('https');
var http = require('http');
var logger = require('winston');
logger.remove(logger.transports.Console);
logger.add(logger.transports.Console, {colorize: true, timestamp: true})
logger.info('SocketIO > listening on port ');
var app = express();
var http_server = http.createServer(app).listen(3001);
function emitNewOrder(http_server){
var io = socket.listen(http_server);
//first listen to a connection and run the call back function
io.sockets.on('connection', function (socket) {
socket.on("new_order", function(data){
console.log(data);
//io.emit("new_order", data)
})
})
}
emitNewOrder(http_server);
and i want the data from the emit_test.php file loged in a reciever php file
with the code
<script>
var socket = io.connect("http://localhost:3001");
socket.on("new_order", function (data) {
console.log(data);
});
</script>
but on running the servers i get an error :
Fatal error: Uncaught UnexpectedValueException: The server returned an unexpected value. Expected "HTTP/1.1 101", had ""
Any help please?
I had the same problem.
I fixed it by changing the version of ElephantIO.
in the emit_test.php I change:
use ElephantIO\Engine\SocketIO\Version1X;
$version = new Version1X("http://localhost:3001");
to this version
use ElephantIO\Engine\SocketIO\Version2X;
$version = new Version2X("http://localhost:3001");
I'm using Node.js (on AWS Lambda for alexa skill) to request my web server for a JSON file. But my server responds with a 'Javascript' not supported error html.
This is my code:
function httpsGet(myData, callback) {
// Update these options with the details of the web service you would like to call
var options = {
host: 'alexa0788.byethost24.com',
port: 80,
path: '/sample.php',
method: 'GET',
};
var req = http.request(options, res => {
res.setEncoding('utf8');
var returnData = "";
res.on('data', chunk => {
returnData = returnData + chunk;
});
res.on('end', () => {
console.log(returnData);
var pop = JSON.parse(returnData).firstName + JSON.parse(returnData).lastName;
callback(pop); // this will execute whatever function the caller defined, with one argument
});
});
req.end();
}
How can I make my server respond with the intended json and not force the client to support javascript? At the moment, I'm having a php file output the json. I tried calling a .json file too directly, instead of making a php file output json, but I see the same error.
I'm trying to access a mysql database using node.js. I simply run the following command in cmd prompt:
C:\rest-server> node bin/www
and it displays this message:
Express server listening in port 80
and I've the .js file as follows which the localhost access at port 80:
var express = require('express');
var router = express.Router();
var async = require('async');
var util = require('../utils/util');
var db = require('../utils/database');
var connection = db.connection();
router.get('/login', function (req, res) {
if (req.session.manager) {
return res.redirect('/');
}
if (req.query.tip == 'error') {
var tip = 'username or password incorrect!';
} else {
var tip = null;
}
res.render('login', { tip: tip });
});
router.post('/login', function (req, res) {
var username = req.body.username;
var password = req.body.password;
var sql = 'SELECT * FROM restaurant_accounts WHERE ra_name=?';
connection.query(sql, [username], function (err, result) {
if (err) throw err;
if (result.length == 0) {
return res.redirect('/manager/login?tip=error');
}
var account = result[0];
if (!util.checkHash(password, account.ra_password)) {
return res.redirect('/manager/login?tip=error');
}
connection.query('SELECT * FROM restaurants WHERE rest_owner_id=?', [account.ra_id], function (err, result) {
if (err) throw err;
var restaurant = result[0];
req.session.manager = {
id: account.ra_id,
name: account.ra_name,
rest_id: restaurant.rest_id,
rest_name: restaurant.rest_name
};
res.redirect('/');
});
});
});
router.get('/logout', function (req, res) {
req.session.destroy();
res.redirect('/manager/login');
});
module.exports = router;
When I type localhost:80 on my browser it displays the following screen:
But ofcourse since the database is not linked, I can't get past this step and it shows the "localhost refused to connect" error!
I already have a .sql database with necessary tables created. How do I link these two so I can login from the login page?
EDIT: database.js
var mysql = require('mysql');
var c = mysql.createConnection({
host : 'localhost',
user : 'bjtu',
password : 'bjtu',
database : 'restaurant'
});
// enable error logging for each connection query
c.on('error', function(err) {
console.log(err.code); // example : 'ER_BAD_DB_ERROR'
});
exports.connection = function() {
return c;
};
CONSOLE ERROR FOR SAMPLE.JS
if (err) throw err;
^
Error: ER_ACCESS_DENIED_ERROR: Access denied for user 'me'#'localhost' (using password: YES)
at Handshake.Sequence._packetToError (C:\Mrestro\RESTaurant_backend-master\rest-server\node_modules\mysql\lib\protocol\sequences\Sequence.js:51:14)
at Handshake.ErrorPacket (C:\Mrestro\RESTaurant_backend-master\rest-server\node_modules\mysql\lib\protocol\sequences\Handshake.js:103:18)
at Protocol._parsePacket (C:\Mrestro\RESTaurant_backend-master\rest-server\node_modules\mysql\lib\protocol\Protocol.js:280:23)
at Parser.write (C:\Mrestro\RESTaurant_backend-master\rest-server\node_modules\mysql\lib\protocol\Parser.js:74:12)
at Protocol.write (C:\Mrestro\RESTaurant_backend-master\rest-server\node_modules\mysql\lib\protocol\Protocol.js:39:16)
at Socket.<anonymous> (C:\Mrestro\RESTaurant_backend-master\rest-server\node_modules\mysql\lib\Connection.js:109:28)
at emitOne (events.js:77:13)
at Socket.emit (events.js:169:7)
at readableAddChunk (_stream_readable.js:153:18)
at Socket.Readable.push (_stream_readable.js:111:10)
--------------------
at Protocol._enqueue (C:\Mrestro\RESTaurant_backend-master\rest-server\node_modules\mysql\lib\protocol\Protocol.js:141:48)
at Protocol.handshake (C:\Mrestro\RESTaurant_backend-master\rest-server\node_modules\mysql\lib\protocol\Protocol.js:52:41)
at Connection.connect (C:\Mrestro\RESTaurant_backend-master\rest-server\node_modules\mysql\lib\Connection.js:136:18)
at Object.<anonymous> (C:\Mrestro\RESTaurant_backend-master\rest-server\utils\sample.js:9:12)
at Module._compile (module.js:409:26)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Function.Module.runMain (module.js:441:10)
at startup (node.js:139:18)
The npm module mysql should do the trick.
Basic connect would look like this:
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'me',
password : 'secret',
database : 'my_db'
});
connection.connect();
connection.query('SELECT 1 + 1 AS solution', function(err, rows, fields) {
if (err) throw err;
console.log('The solution is: ', rows[0].solution);
});
connection.end();
Probably soon you would like to have a look at MongoDB. Which you can connect to using module mongoose, for example.
Update:
Try to set port to your connection object in database.js. Like this:
var mysql = require('mysql');
var c = mysql.createConnection({
host : 'localhost',
user : 'bjtu',
password : 'bjtu',
database : 'restaurant',
port : 90
});
// enable error logging for each connection query
c.on('error', function(err) {
console.log(err.code); // example : 'ER_BAD_DB_ERROR'
});
exports.connection = function() {
return c;
};
The default port is 3306, which doesnt look like your case :)
And I suggest you to look into mysql pools.