Node js - Socket is not connecting with https - php

I am trying to connect to a socket.io-client using the following code: It works HTTP local server. But not working in the HTTPS Live server.
Server:
var express = require('express');
var app = module.exports = express();
var https = require('node:https');
var fs = require('node:fs');
var server = https.createServer({
key: fs.readFileSync("path/key.pem",'utf8'),
cert: fs.readFileSync("path/cert.pem",'utf8'),
requestCert: true,
rejectUnauthorized: false
},app);
var eio = require('engine.io').attach(server);
const io = require('socket.io')(server, {
cors: { origin: "*"}
});
io.on('connection', (socket) => {
console.log('connection');
socket.on('sendChatToServer', (message) => {
socket.broadcast.emit('sendChatToClient', message);
console.log(message);
});
socket.on('disconnect', (socket) => {
console.log('Disconnect');
});
});
server.listen(3000, () => {
console.log('Server is running');
});
Client:
let socket = io("https://mydomain:port");
socket.emit('sendChatToServer', textmessage);

Related

Laravel socket.io doesn't work, failed socket connect, how to fix?

I am trying to create a live chat. Socket.io and node.js
I can't connect the user to my channel.
https://domen.com:8005/socket.io/?EIO=3&transport=polling&t=NYHmcgH :failed
Here is my server.js
var app = require('express')();
var https = require('https').Server(app);
var io = require('socket.io')(https);
var Redis = require('ioredis');
var redis = new Redis();
var users = [];
https.listen(8005, function () {
console.log('Listening to port 8005');
});
io.on('connection', function (socket) {
socket.on("user_connected", function (user_id) {
console.log("user connected " + user_id);
// users[user_id] = socket.id;
// io.emit('updateUserStatus', users);
// console.log("user connected "+ user_id);
});
and here is my blade template
<script>
$(function () {
let user_id = "{{ auth()->user()->id }}";
console.log(user_id);
let ip_address = 'domen.com';
let socket_port = '8005';
let socket = io(ip_address + ':' + socket_port);
});
socket.on('connect', function () {
socket.emit('user_connected', user_id)
});
</script>
express with https needs some keys
var https = require('https')
var app = express()
https.createServer({
key: fs.readFileSync('server.key'),
cert: fs.readFileSync('server.cert')
}, app)
.listen(8005, function () {
console.log('Example app listening on port 8005! Go to https://domen.com:3000/')
})
i think you should try first with http, if your code works well then you can upgrade to https
var io = require('socket.io')(http);
http.listen(8005, function () {
console.log('Listening to port 8005');
});
in client side :
let ip_address = 'http://domen.com';

Socket.io Error on server

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.

How to post JSON data to another server by lambda script

I am trying to send some JSON data(Fetched From DaynamoDB) to another server from AWS lambda function but while giving the URL in the script :
'use strict';
const https = require('https');
exports.handler = (event, context, callback) => {
var options = {
hostname: 'https://www.corecomputersystem.com',
path: '/getSyncData.php',
port : 432,
method: 'POST',
headers: {
'Content-Type': 'application/json',
}
};
event.Records.forEach((record) => {
console.log(record.eventID);
console.log(record.eventName);
console.log('DynamoDB Record: %j', record.dynamodb);
var res = record.dynamodb;
const req = https.request(options, (res) => {
let body = "";
console.log('Status:', res.statusCode);
console.log('Headers:', JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', (chunk) => body += chunk);
res.on('end', () => {
console.log('Successfully processed HTTPS response');
// If we know it's JSON, parse it
if (res.headers['content-type'] === 'application/json') {
body = JSON.parse(body);
}
callback(null, body);
});
});
req.on('error', callback);
req.write(JSON.stringify(event.data) + "");
req.end();
//context.succeed();
});
};
it's throwing following error,
{
"errorMessage": "getaddrinfo ENOTFOUND https://www.corecomputersystem.com https://www.corecomputersystem.com:432",
"errorType": "Error",
"stackTrace": [
"errnoException (dns.js:26:10)",
"GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:77:26)"
]
}
and if I uncomment the context.succeed(), there is no error, I need help for identifying the error.
Just for deeply with #at0mzk says, a hostname never take any port number, so any prefix like [http, https, smb, nfs]:// will throw an error any where a hostname is requested.
(http://localhost === localhost:80)
remove https:// from hostname variable.
var options = {
hostname: 'www.corecomputersystem.com',
path: '/getSyncData.php',
port : 432,
method: 'POST',
headers: {
'Content-Type': 'application/json',
}
see docs.
Before making HTTPS request we can use :
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
so it will not ask for authorization.
Another way we can add a key in option before requesting HTTP:
rejectUnauthorized: false
It will not ask for self asigned certificate.
This is what I was searching for.
This worked for me.
In lambda use the following node js.
const https = require('https');
var querystring = require("querystring");
const doPostRequest = (event) => {
//parameters to post
const params = {
name: "John",
title: "Developer",
userid: 123
};
var qs = querystring.stringify(params);
var qslength = qs.length;
return new Promise((resolve, reject) => {
const options = {
host: 'example.com',//without https or http
path: '/yourpath/yourfile.php',
method: 'POST',
port: 443, // replace with 80 for HTTP requests
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': qslength
}
};
var buffer = "";
//create the request object with the callback with the result
const req = https.request(options, (res) => {
resolve(JSON.stringify(res.statusCode));
res.on('data', function (chunk) {
buffer+=chunk;
});
res.on('end', function() {
console.log(buffer);
});
});
// handle the possible errors
req.on('error', (e) => {
reject(e.message);
});
//do the request
req.write(qs);
//finish the request
req.end();
});
};
exports.handler = async (event) => {
try {
const result = await doPostRequest(event);
console.log('result is:️ ', result);
//️️ response structure assume you use proxy integration with API gateway
return {
statusCode: 200,
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(result),
};
} catch (error) {
console.log('Error is:️ ', error);
return {
statusCode: 400,
body: error.message,
};
}
};
For some reason lambda didnt show the response for me other than 200. So I had to create a logfile on my server to verify that it was sending the POST values. From there you can use json_encode to show the posted string or just echo the POST values
$inputJSON = json_encode($_POST);
$input = json_decode($inputJSON, TRUE);
$log = "Data: ".$_SERVER['REMOTE_ADDR'].' - '.date("F j, Y, g:i a").PHP_EOL.
"Data: ".$inputJSON.PHP_EOL.
"Data: ".$input.PHP_EOL.
"Data: ".$_POST['name'].PHP_EOL.
"Data: ".$_POST['title'].PHP_EOL.
"Data: ".$_POST['userid'].PHP_EOL.
"-------------------------".PHP_EOL;
//Save string to log, use FILE_APPEND to append.
file_put_contents('./log_'.date("j.n.Y").'.log', $log, FILE_APPEND);

Changing node.js server to Apache server

I was working with react-webpackage and running the project into node.js
Now due to demand , i have to add some php files in the project but i don't know how to add php file in my project and now transfer my project from node.js to Xampp and run my project with xampp... can you please guide me with that.
I am using this webpack "https://github.com/srn/react-webpack-boilerplate".
And my webpack index.js file looks like this.
'use strict';
var fs = require('fs');
var path = require('path');
var express = require('express');
var app = express();
var compress = require('compression');
var layouts = require('express-ejs-layouts');
app.set('layout');
app.set('view engine', 'ejs');
app.set('view options', {layout: 'layout'});
app.set('views', path.join(process.cwd(), '/server/views'));
app.use(compress());
app.use(layouts);
app.use('/client', express.static(path.join(process.cwd(), '/client')));
app.disable('x-powered-by');
var env = {
production: process.env.NODE_ENV === 'production'
};
if (env.production) {
Object.assign(env, {
assets: JSON.parse(fs.readFileSync(path.join(process.cwd(), 'assets.json')))
});
}
app.get('/*', function(req, res) {
res.render('layout', {
env: env
});
});
var port = Number(process.env.PORT || 3001);
app.listen(port, function () {
console.log('server running at localhost:3001, go refresh and see magic');
});
if (env.production === false) {
var webpack = require('webpack');
var WebpackDevServer = require('webpack-dev-server');
var webpackDevConfig = require('./webpack.config.development');
new WebpackDevServer(webpack(webpackDevConfig), {
publicPath: '/client/',
contentBase: './client/',
inline: true,
hot: true,
stats: false,
historyApiFallback: true,
headers: {
'Access-Control-Allow-Origin': 'http://localhost:3001',
'Access-Control-Allow-Headers': 'X-Requested-With'
}
}).listen(3000, 'localhost', function (err) {
if (err) {
console.log(err);
}
console.log('webpack dev server listening on localhost:3000');
});
}
basically i want to declare some variables in php and fetch them to javascript.so just want to add one file in webpack(file named as index.php) and then all my project work normally
Thanks.
You can't run express on the same port of xampp, you have to use different ports (or different servers) to serve the php file.

How can I call localhost from localhost (laravel, nodejs)?

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}`);
});

Categories