Can't access NodeJS instance through NGINX - javascript

I want to deploy a server running on NodeJS to my cloud server.
The server:
OS: CentOS 6.5
External IP: 123.125.130.102
NodeJS code:
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('Hello World');
});
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("http://%s:%s", host, port)
});
I am running an instance on this server.
NGINX config:
server {
listen 80;
server_name 123.125.130.102;
location / {
proxy_pass http://localhost:8081/;
}
}
But I can't seem to access my node application on http://123.125.130.102:80.
I'm new to NodeJS and I don't what is wrong.

Related

Heroku: What will be the hostname and port of my deployed socket.io app

I have a socket.io app that I want to host on heroku. This is my first heroku deployment and I am not sure what is the hostname and port of my app is. This is how the server.js file is :
const http = require('http').createServer();
const questions = require('./Questions');
const dares = require('./Dares');
const rathers = require('./WYRather');
const nhie = require('./NHIE');
const io = require('socket.io')(http, {
cors: { origin: "*"}
});
http.listen(process.env.PORT || 8080, () => {
console.log("Server listening on: http://localhost:8080");
});
The hostname is ${your-project-name}.herokuapp.com.
The port cannot be determined until it gets deployed, which will be process.env.PORT.

How can I connect 2 node.js app eachother ?(one of client app -one of server app) + socket.io

I'm new to node.js and socket.io. They asked me to divide the connect4 game (I made with Javascript,node.js, express, socket.io, jquery ) into 2 separate apps (server app and client app).
The node.js of these two Apps must be connected to each other. In other words, I need to connect Client App's Node application to the port of the Server App's node application. (They said I should have 2 working ports belonging to 2 applications)
(Before divided the app it was working normal; when client give the url of the room he can play with his friend, game start and over normally But now everything mixed.)
Connect 4 game was working when client and server in the same App but now I cant do something like that
"
app.get('/:room([A-Za-z0-9]{9})', function(req, res) //app.set('view engine', 'html'); //res.status(200).sendFile(__dirname+'./index.html');
"
But my main problem is I couldn't connect from Client App nodejs to Server app nodejs .
Code part of the server app;
const express = require('express');
const cors = require('cors');
const app = express();
const http = require('http').createServer(app);
const io = require('socket.io')(http ,{
cors: {
origin: '*',
methods: ['GET', 'POST'],
},
serveClient: false,
pingInterval: 5000,
});
const port = process.env.PORT || 4000;
const { randomNumeric } = require('./utils.js');//I want random room key for later
// TODO: IF CORS DOES NOT WORK, TRY TO USE IT IN EXPRESS SERVER
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET, POST');
res.header('Access-Control-Allow-HEADERS', 'Content-Type');
});
io.listen(port, () => { //Its not working :(
console.log("çalışıyor");
console.log(`Server started at ${port}`);
});
And Client App node.js code;
var express = require('express'),
game_logic = require('./game_logic'),
app = express(),
server = require('http').createServer(app),
port = Number(process.env.PORT || 3000);
server.listen(port);
console.log('Node.js web server port 3000 de çalıştı')
/*routing*/
app.use("/css", express.static(__dirname + '/css'));
app.use("/js", express.static(__dirname + '/js'));
app.use("/img", express.static(__dirname + '/img'));
app.get('/', function(req, res) {
res.sendFile(__dirname+'/index.html');
});
And in Client App I have App.js for socket.io connect
$(function(){
var socket = io.connect(),
player = {},
yc = $('.your_color'),
oc = $('.opponent_color'),
your_turn = false,
url = window.location.href.split('/'),
room = url[url.length-1];
after that I have code for connect socket.io like socket.on and socket.emit
when I run this 2 App and open the local3000 I just saw empty game board nothing happened,
Can you help me about this and I really need to some links about this topic. Thank u

How to call node api response in socket.io server

Scenario: Creating a Node API (GET) calling that API in socket.io Node server and calling this socket server in angular client.
What i have done: Created a node API for get request and post and created a socket server I tried to consume the app.
Issues: 1. I tried to consume the API but was unable to get the data in the socket server and 2. If it works, also how can i get the socket data on button click in angular application?
Note: I'm running Node API on 3000 server and running socket server on 3001.
Below is my code
Node api code runnning on 3000 port:
const express = require('express')
const bodyParser = require('body-parser');
const cors = require('cors');
const app = express()
const port = 3000
let books = [{
"isbn": "9781593275846",
"title": "Eloquent JavaScript, Second Edition",
"author": "Marijn Haverbeke",
"publish_date": "2014-12-14",
"publisher": "No Starch Press",
"numOfPages": 472,
}];
app.use(cors());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.post('/book', (req, res) => {
const book = req.body;
// output the book to the console for debugging
console.log(book);
books.push(book);
res.send('Book is added to the database');
});
app.get('/book', (req, res) => {
res.json(books);
});
app.listen(port, () => console.log(`Hello world app listening on port ${port}!`));
Socket .io server running on 3001
var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket.io')(http);
const apiUrl="http://localhost:3000/book"
io.on('connection', function (socket) {
socket.on('getBanners', function(data){
request.get(apiUrl,function (error, response, body){
console.log(body)
socket.emit('result', {res:JSON.parse(body)})
})
});
});
http.listen(3001, function(){
console.log('listening on *:3001');
});
Note: Node API server --> socketio server (not client)
I wouldn't recommend going by that design you have.
Unless there is a very specific/important reason to have the socket.io server on a different port than the HTTP server, I would recommend having your socket.io server upgraded from the HTTP server itself.
eg.
In bin/www:
const { initSocketIOServer } = require('../socket-server');
const port = normalizePort(process.env.PORT || '3001');
app.set('port', port);
/**
* Create HTTP server.
*/
const server = http.createServer(app);
initSocketIOServer(server);
In socket.server.js
module.exports.initSocketServer = (server) => {
io = require('socket.io')(server);
io.on('connection', (socket) => {
console.log('client connected');
socket.on('getBanners', (event) => {
// handle getBanners event here
});
});
};
However, going by your example, if you really need to make a request to the HTTP server to fetch data, you might want to use the HTTP library:
socket.on('getBanners', (event) => {
http.get({
hostname: 'localhost',
port: 3000,
path: '/book',
agent: false // Create a new agent just for this one request
}, (res) => {
// Do stuff with response, eg.
const socketResponse = processBooks(book);
socket.emit('result', socketResponse);
});
});
You can use any node package for requests like request https://github.com/request/request
here

Node.js Express.js sslforfree not working

I am using sslforfree for creating an https server with node.js, express.js. But whenever I try to access https://localhost it shows me error 403: access denied. My folder structure like this.
and my server.js goes here
var express = require('express')
, fs = require('fs')
, passport = require('passport')
, logger = require('mean-logger')
, http = require('http')
, https = require('https')
, path = require('path')
var env = process.env.NODE_ENV || 'production'
, config = require('./config/config')[env]
, auth = require('./config/middlewares/authorization')
, mongoose = require('mongoose')
var db = mongoose.connect(config.db)
var models_path = __dirname + '/app/models'
fs.readdirSync(models_path).forEach(function (file) {
require(models_path+'/'+file)
})
require('./config/passport')(passport, config)
var app = express()
require('./config/express')(app, config, passport)
require('./config/routes')(app, passport, auth)
var options = {
key: fs.readFileSync(path.resolve(__dirname,'config/ssl/patarboi.key')),
cert: fs.readFileSync(path.resolve(__dirname,'config/ssl/patarboi.crt')),
ca: fs.readFileSync(path.resolve(__dirname,'config/ssl/patarboi.ca'))
};
/*app.listen(port)
console.log('Express app started on port '+port)*/
logger.init(app, passport, mongoose)
// expose app
exports = module.exports = app
var port = process.env.PORT || 443
var server = https.createServer(options, app);
server.listen(port, function () {
console.log('server at port '+port);
});
You are trying to run your server on port 443. Remember your service needs to have root permission to listen to this PORT.
And most probably 443 will be in use already. You can check by netstat -a and see if 443 is in the list.
In windows, if you're using skype. This would also create some trouble when you try to use 443 PORT.

Getting Error when I deploy ext js app in node server

I am trying to deploy my ext js app in node server. Steps i have followed.
1.Created a Extjs app using sencha cmd and had used sencha app build to build my app
Once after building successfully i have taken my app in build-->production folder to my node server folder.
below screenshot contains dbview(client) files
When i start my node server and run my applicaiton using http://localhost:3000 getting following error in my console
Please find my server code
var express = require('express')
var app = express()
app.get('/', function (req, res) {
res.sendFile(__dirname+"\\dbview\\index.html");
})
var server = app.listen(3000, function () {
var host = server.address().address
var port = server.address().port
console.log('Example app listening at http://%s:%s', host, port)
})
Help me with the problem
You need to mount the directory so that express knows to look for static content there, or you could go the long way about it and create a specific route handler for that file:
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.sendFile(__dirname+"\\dbview\\index.html");
});
// THIS IS WHAT YOU NEED
app.use(express.static(__dirname));
// OR THE LONG WAY
app.get('/app.json', function(req, res) {
var options = {
root: __dirname,
dotfiles: 'deny',
headers: {
'x-timestamp': Date.now(),
'x-sent': true
}
};
res.set('Content-Type', 'application/json');
res.sendFile('app.json', options);
});
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
See the Express Documentation for further details.

Categories