Get Node js Server Url - javascript

I am new to node.js. I just installed node.js on my production server it was installed correctly and node.js is running on my putty cli the problem is I cannot access it on my browser. I think my problem is because I installed created my server on a subdirectory inside a subdomain e.g. subdomain.example.com here is my code
var http = require('http');
//create a server object:
http.createServer(function (req, res) {
res.write('Hello World!'); //write a response to the client
res.end(); //end the response
}).listen(3000); //the server object listens on port 8080
Now I am trying to access the node.js server by going to this address subdomain.example.com:3000 but I am getting no results. Please help Thanks!

Related

How to access the Node server hosted in my laptop from a device in another network?

I have written this test.js
var http = require("http");
http.createServer(function (request, response) {
// Send the HTTP header
// HTTP Status: 200 : OK
// Content Type: text/plain
response.writeHead(200, {'Content-Type': 'text/plain'});
// Send the response body as "Hello World"
response.end('Hello World\n');
}).listen(8080,'192.168.1.5');
// Console will print the message
console.log('Server running at http://192.168.1.5:8080/');
I runned the command node test.js
C:\Users\ShalomAlexander\Documents>node test.js
Server running at http://192.168.1.5:8080/
This URL is accessible from my laptop and devices connected to the same wifi network. but I'm not able to access it when I switch from wifi network to mobile network on my smartphone.
so how can I make it work on other devices in different networks?
You need to either...
host your app on a public server (e.g. a cloud provider) or
make your machine publicly available
Second option requires you to do a port opening & proper forwarding from your router to your machine. Also, you probably want some dynamic DNS entry for your IP, because in general you're not having a fixed IP. Just some hints for this - I don't know what your use case is.
You need to host your NodeJs application on a server(eg: heroku). Then you can access it with the hosted URL.
Please check the documentation on deploying your NodeJs application in Heroku.
https://devcenter.heroku.com/articles/getting-started-with-nodejs

Node.js client can't see data from Express server

I am setting up a Client/Server communication between my tablet and my PC. My Client cant get any data from the server, what am I doing wrong.
My PC is running a Node.js server (using Express) and my tablet runs a client written in Node.js (using Express). I can access the server via the browser and get the data, but not through the javascript code.
My SERVER code is:
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('App requested a connection');
});
app.listen(3000, () => console.log('Listening on port 3000!'));
app.get("/boxes", function (req, res)
{
//res.send(req.params[0]);
res.send("All boxes are in the basement");
});
My CLIENT code is:
const express = require('express');
const app = express();
console.log("Client working ...");
app.get("http://127.0.0.1:3000/boxes", function (req, res)
{
console.log("inside...");
console.log(res);
});
The CLIENT should return "All boxes are in the basement" and I get this when I use a browser but it doesn't work if I run the client code. The only message I get from client is "Client working ...".
Does anybody know what I am doing wrong?
Cheers
Express is a library for setting up and configuring an http server for incoming requests. It does not make outgoing requests to other servers. So, your client code is not a client at all.
Several problems here:
127.0.0.1 refers to your local device so your client is referring to itself when it uses 127.0.0.1.
In your client app.get("http://127.0.0.1:3000/boxes") is not a request for data. That attempts to set up an Express route for incoming requests as if you were declaring a second server. But, it's not even done correctly because you would only use the path there.
For a client to make a request of some other server, you would need to use a library call that actually does http requests. For example, you could do something like this:
Code:
const rp = require('request-promise');
rp.get("http://ipaddressOfServer:3000/boxes").then(data => {
// have response here
}).catch(err => {
// error here
});
I chose to use the request-promise library, but there are multiple different ways to make an http request. You can also use http.get() (lower level), request() (from the request library) or axios() from the axios library, etc...
Note, the computer your server is on (assuming it's running a desktop OS) will also have to probably turn of it's local firewall (e.g. windows firewall) or set up a specific rule to allow incoming connections on port 3000. Without that, the incoming connection will be blocked (for security reasons).

Problems using socket.io, socket.io.js not found

I receive this error in console GET http://localhost/socket.io/socket.io.js 404 (Not Found). I used npm install to install express and socket.io. Everytime I try to access localhost:3000 it downloads a file instead of displaying chat.php
This is my javascript code
var express = require('express')
var app = express()
, http = require('http')
, server = http.createServer(app)
, io = require('socket.io').listen(server);
server.listen(3000);
users = [];
connnection = [];
console.log('Server running!');
app.get('/',function(req, res){
res.sendFile(__dirname + '/game.php');
});
io.sockets.on('connection', function(socket){
connections.push(socket);
console.log('Connected: %s sockets connected', connections.length);
//Disconnect
socket.on('disconnect', function(data){
connections.splice(connections.indexOf(socket),1);
console.log('Disconnected: %s sockets connected', connections.length);
});
});
And this is what I added into php file
<script src="/socket.io/socket.io.js"></script>
<script>
$(function(){
var socket=io.connect();
});
</script>
res.sendFile(__dirname + '/game.php'); just sends a raw PHP file to the browser client. Instead, what you need to send to the browser is HTML. So, you either have to change your app to run in node.js and not PHP or you have to exec that PHP file and grab its output and send that to the browser.
Normally, if you wanted your page to be generated via PHP, you wouldn't be using node.js at all - you'd just be using PHP. If the only reason you brought node.js into the equation is because of socket.io, then maybe you should be using socket.io directly with PHP which you can read about in this question. You could use a hybrid of node.js and PHP, but it's unlikely to be all that efficient if you're using node.js to run your PHP. For that case, you would probably be better off running socket.io in node.js on a different port number, enabling cross origin access and just leaving your PHP to be PHP.
I found the working solution with PHP here https://github.com/jdutheil/nodePHP. I tested it and it is working just great.

Running https not on 443 how is this possible?

If I hit my domain on any other port other than 443 I get the error below. How is it possible then to use nodejs https on different port?
Secure Connection Failed
An error occurred during a connection to mysite:8080. SSL received a record that exceeded the maximum permissible length. (Error code: ssl_error_rx_record_too_long)
For example, in the example given in the documentation they use port 8000.
// curl -k https://localhost:8000/
var https = require('https');
var fs = require('fs');
var options = {
key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem')
};
https.createServer(options, function (req, res) {
res.writeHead(200);
res.end("hello world\n");
}).listen(8000);
Using CentOS 6.
record_too_long often/usually means you sent non-SSL-data to a client expecting SSL.
Try to visit your site and port via HTTP (not HTTPS). If it works, you have accidentally bound an HTTP server to it, not an HTTPS server.
At this very moment I have a Node.js server running on port 3000 using HTTPS.
SSL_ERROR_RX_RECORD_TOO_LONG seems to indicate that there's a problem with the hostname (Source)
The error you've included mentions mysite:8080 which tells me that you're trying to connect to mysite:8080 and that that address doesn't exist.
To debug this, try accessing the URL through a browser or by setting up a regular HTTP and see whether it's accessible.

Cross domain connections in Node.js

I'm in the process of learning Node and have a question I can't seem to find the answer to. In the following example of a minimalistic chat server the node server expects the client page to reside in the same directory as the server file, if I was building a client side app for a mobile device, how would I send the data back to the proper client?
var fs = require('fs')
, http = require('http')
, socketio = require('socket.io');
var server = http.createServer(function(req, res) {
res.writeHead(200, { 'Content-type': 'text/html'});
**res.end(fs.readFileSync(__dirname + '/index.html'));**
}).listen(8080, function() {
console.log('Listening at: http://localhost:8080');
});
socketio.listen(server).on('connection', function (socket) {
socket.on('message', function (msg) {
console.log('Message Received: ', msg);
socket.broadcast.emit('message', msg);
});
});
Are you running into this problem? If so, perhaps using the phonegap iOS / Android plugins for WebSockets may help you.
For reference, here is what res.end(fs.readFileSync(__dirname + '/index.html')); means:
Synchronously read the contents of the file index.html (located in the server's current directory)
End the HTTP response after sending the contents of the file over the network to the client who requested the page (could be the local machine, a phone, a computer on the internet -- anyone who has access to the server). In other words, node is acting as an HTTP server for the page index.html
Index.html presumably contains some socket-related code that instructs the client to connect to the socket on the server (the server's socket is created by socketio.listen(server))

Categories