I'm trying to begin the backend of a MEAN project I'm working in right now. It's a project for testing purposes, and Node is still in my TO-DO list.
So, I today wrote this simple server to have something to begin with, and at least being able to see my Angular page and begin to create a simple server-side API. The example can be seen in many websites:
//Lets require/import the HTTP module
var http = require('http');
//Lets define a port we want to listen to
const PORT=8080;
//We need a function which handles requests and send response
function handleRequest(request, response){
response.end('It Works!! Path Hit: ' + request.url);
}
//Create a server
var server = http.createServer(handleRequest);
//Lets start our server
server.listen(PORT, function(){
//Callback triggered when server is successfully listening. Hurray!
console.log("Server listening on: http://localhost:%s", PORT);
});
Well, the problem is quite simple: when I try to access to localhost/myproject, it just doesn't work. Happens the same for 127.0.0.1/myproject. The js file is in the same folder than the project folder, so I should be able to access this way if the server were working.
I looked for an already answered question and found one in which you have to deactivate a directive in Windows Firewall... but that directive doesn't exist in mine.
So, any help with this?
Please add port 8080 to your access url 127.0.0.1:8080/myproject.
Related
I have a Python script that I have written that an utilizes an API to retrieve weather information, its just a simple terminal print script for right now. I am starting to learn more about HTML/JS and am wondering where I could start to learn how to pass information from my web pages to scripts.
Eventually what I am trying to work towards is passing a zip code string input from an HTML form over to my Python script on my local machine, and then have the script return data to my webpage.
The problem is, I have no idea where to start, or where even to start looking for information. For example, I understand that you can pass values to a server side application & that is kinda what I'm simulating here.
If you want to run your python script from your websites, you could use a server for that. Given that you are already into Javascript, I suggest that you create a server using a popular JS framework called Express. Express is designed for NodeJS, a JS runtime.
Once you setup your Express server, you can start creating routes and integrate them into your websites by making asynchronous calls with utilities like fetch or axios. For example, you can create a sample app like this:
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('Hello World!');
});
app.use('/run-script', function (req, res) {
res.send('Script run!');
};
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
If you look closer, app.use() allows you to define routes. When a user or a JS script calls this route, the function gets executed. For example, inside the route run-script you could execute yours:
app.use('/run-script', function(){
const spawn = require("child_process").spawn;
const pythonProcess = spawn('python',["path/to/script.py", arg1, arg2, ...]);
});
As you see, there are numerous possibilities. For more info on calling python scripts from node, see this stackoverflow question.
You could start digging into NodeJS in general. For that, a good place to start is the official guides.
Please let me know if this answer was useful to you.
I am trying to run a NodeJS cron at a set interval using cron-job.org, but they don't have any documentation about how to actually run the script.
Basically the service visits a URL that you provide at a set interval, but I am specifically confused about what kind of code I can put on the endpoint (specifically what type of code will actually run). Can someone provide an example of what I would put at the endpoint URL?
You can do something really simple using either the HTTP module in Node.js or the popular Express module. Using express you can do something really simple like:
var express = require('express');
var app = express();
app.get("/test", function(req, res, next){
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify({ status: 'OK', timeStamp: new Date().toISOString() }));
});
console.log('Express listening.. on 3000');
app.listen(3000);
You can really run anything you like in the /test endpoint, though when it's being called from cron-job.org they'll probably stop if you keep throwing back 400 errors at them or the script takes really long to execute.
You'd call this using the url
http://yourdomain:3000/test
And of course you might well want to change the port number and path!
cron-job.org only allows you to call an endpoint at a set time interval.
If you want to have some code run at a set interval without worrying about HTTP server, deploying, etc... Check out services like chunk.run
Here's an example code:
https://chunk.run/c/scheduled-run-example
Then you can just select the trigger "Scheduled" like so:
I created simple app to start with socket.io, but when I run it, Chrome(tested in other browsers, result same) eats all of my CPU and makes many requests:
I'm new to sockets, but I'm sure this is not how it should work. The code running in browser is really simple, it should just connect to socket and log all received data to console:
index.html
<!DOCTYPE html>
<html>
<head>
<script src="https://cdn.socket.io/socket.io-1.2.0.js" charset="UTF-8"></script>
</head>
<body>
<script type="application/javascript">
var Sockets = io.connect('http://localhost:4000');
Sockets.on('Test', function (data) {
console.log(data);
});
</script>
</body>
</html>
Also, my server file looks like this:
server.js
var app = require('express')();
var http = require('http').Server(app);
var bodyParser = require("body-parser");
var io = require('socket.io')(http);
var port = 4000;
http.listen(port, function () {
console.log('Server running at port ' + port);
});
var urlencodedParser = bodyParser.urlencoded({extended: false});
app.post('/', urlencodedParser, function (req, res) {
if (!req.body) return res.sendStatus(400);
var post = req.body;
io.emit("Test", post.data);
console.log(post.data);
res.send('true');
});
io.on('connection', function(socket){
console.log('a user connected');
socket.on('disconnect', function(){
console.log('user disconnected');
});
});
When I run the server node server.js, I got the Server running at port 4000 message and everything seems fine. But when I open the index.html in my browser, the node console is spammed by a user connected messages. Instead of connecting one client, the browser makes dozens of requests every second. When I close the browser, there is no output for some time, and then the node console is spammed by user disconnected messages.
This server should redirect all data sent via POST to connected sockets. When I make this POST request, the node server receives it (I know because it print's it into node console). But it's not received by the socket client, as there is no output in browser console (but the browser still makes dozens of new connections every second.
What is wrong here? First I thought I just messed up, so I went back and copy-pasted code from tutorial I found (not in English, but in Czech), but nothing changed. The tutorial has a lot of positive feedback, so there is propably something wrong with my computer. But what?
I had experienced the same issue, by following an example where the client was using the source of socket.io from this cdn: https://cdn.socket.io/socket.io-1.2.0.js
Tons of clients created whenever I tried to run the file (no matter if i just double clicked the html file, or if I put it under a web server, like IIS) . I then realized it might be an older version, and I just took the latest one released from this source: https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.4/socket.io.js
Everything works fine now.
Hope this helps
So to find what exactly was wrong, I downloaded example socket chat from socket.io website. When I runned it, I experienced exactly the same wrong behaviour - browser is opening many socket connections every second instead of keeping one.
So I deleted node_modules folder and used npm to install these modules again and whoa, it worked. So propably the files just corrupted during download or whatever it was, but doing the same procedure again was working this time.
Your configuration of running that page from a different web server than your socket.io server is on won't work as you have it. It will take one of three changes to make it work:
You can use the "same origin" for the web page and the socket.io connection by loading the web page from the same server that your socket.io. That means you need to load the web page directly from your socket.io web server.
You can configure your socket.io web server to accept cross origin connections (CORS connections).
You can configure your socket.io client to connect directly using webSocket without doing socket.io's usual preview with a regular http request.
If you're testing something you intend to deploy for real, you may as well just make your existing socket.io web server server your web page and load the web page directly from that.
Another possible cause of a situation like this is an incompatible client and server version of socket.io. You should make absolutely sure that you have the same version of socket.io on client and server. If you get the client socket.io library from /socket.io/socket.io.js from your socket.io web server, the the client version will automatically always match the server version. The way you are loading it from a CDN, you have to manually make sure you have identical versions.
server side code:
var server = require("http").Server(express);
var io = require("socket.io")(server);
server.listen(5000);
io.on('connection', function(client) {
client.on('order', function(data) {
io.emit('place_order',data);
});
});
cilent side code
var socket = io.connect('http://localhost:5000');
socket.on('place_order', function (data) {alert('data.x')})
Somewhere in github I git clone a project and I saw something above. The 3rd line of server side code confused me. Why the author created extra port here? isn't it ok to discard the 3rd line and in the cilent side just connect to the path without port like var socket = io.connect('http://localhost:5000');? Need explanation for socket.io expert here, I'm confused.
btw this code does work..
Why the author created extra port here?
You have to start your server on some port and server.listen(nnn) is one way to do that. If you don't start your server, it isn't actually running and you can't ever connect to it.
Servers must be created and then started on a specific port.
In your particular code example, you've chosen to run your server on port 5000 instead of the more common port 80.
isn't it ok to discard the 3rd line
No. Without it your server will not be running.
If your server is started on port 80, then you don't have to list a port number in the URL since that is the default port number for an http:// connection.
After attaching your socket.io to an HTTP server, it needs to start. This how socket works. Thats what the 3rd line does. So, removing it means you are not starting the server itself, and obviously that wouldn't work.
The port is at 5000 which might look unconventional to you, but this is a standard practise to prevent errors if the PORT 80 is in use, like it often is by other web/internet based applications/servers. But, if that isn't the case feel free to change the port to 80 by replacing the 3rd line as server.listen(80);
For Ref: if you get the error: Error: listen EADDRINUSE :::80 then understand directly that the port wasn't free!!
That is not a socket.io's problem. In a Node.js application you need to specify which port do you want your Node.js runs.
Node.js is a plataform and in the first line you create a server and for that you need to put the port that your server runs.
https://nodejs.org/dist/latest-v6.x/docs/api/http.html#http_http
How can I integrate node.js and socket IO in code igniter.
<script>
// create a new websocket
var socket = io.connect('http://localhost:8000');
// on message received we print all the data inside the #container div
socket.on('notification', function (data) {
var usersList = "<dl>";
$.each(data.users,function(index,user){
usersList += "<dt>" + user.user_name + "</dt>\n" +
"<dd>" + user.user_description + "\n" +
"<figure> <img class='img-polaroid' width='50px' src='" + user.user_img + "' /></figure>"
"</dd>";
});
usersList += "</dl>";
$('#container').html(usersList);
$('time').html('Last Update:' + data.time);
});
</script>
As mentioned in this SO question here. My view file with codeigniter is in localhost/myproject but nodejs listen to port using localhost:8000. So how can I connect socket IO. Like
var socket = io.connect('http://localhost:8000');
//here I need to make socket IO listen to localhost/myproject instead of localhost:8000 .
How is this possible?
I think you're misunderstanding how the socket.io works. You would never listen to your CI view. You would always be sending messages to (and receiving messages from) the NodeJS server on port 8000. Codeigniter's views are simply static, and there is no reason to "listen" to it since it will only load once.
The key point from that answer you referenced:
users will use codeigniter URL and when open the page, i have this script on my CI view page that connects to my Nodejs app
Therefore, you load your browser with the CI view, then listen for events from the NodeJS server through the JavaScript in your CI view.
You can then also push events to the NodeJS server from the JavaScript in your CI view.
Use Dnode, it is an asynchronous RPC system for node.js that makes it talk to php (and vice versa) directly (php side you can call on your codeigniter controller)
I wrote a linkedin post recently about this
https://www.linkedin.com/pulse/make-php-nodejs-talk-each-other-serdar-senay
In the tutorial written for dnode by its founder there's some stale code, so use the code sample in my linkedin post, also dumped below (with better formatting than linkedin):
require ('vendor/autoload.php');
$loop = new React\EventLoop\StreamSelectLoop();
// Connect to DNode server running in port 7070 and call argument with Zing 33
$dnode = new DNode\DNode ($loop);
$dnode-> connect (7070, function ($remote, $connection) {
// Remote is A That Provides Proxy object Methods us all from the Server
$remote-> zing(33, function ($n) Use ($connection) {
echo "n = {$n}\n";
// Once We Have the Result We Can close the connection
$connection->end();
});
});
$loop-> Run();
you can directly link socket.io.js in the codeigniter view.
<script type='text/javascript' src='http://localhost:8000/socket.io/socket.io.js'></script>
then you will be able to make connection to nodejs server from http://localhost/myproject
var socket = io.connect('http://localhost:8000');
However, This way you will do all your client side code in codeigniter view. If you want to use nodejs template engine to send html pages to browser then you can change your node.js server port to 80.
Here's the flow you're going to want to achieve:
1) node.js server setup with socket.io sockets(.on). If you want to have node.js working over socket 80, look into having iptables forward port 80 to port 3000.
2) Add the socket.io client to the code igniter project. You'll be using this to make the initial connection to the node.js/socket.io connection in the CI View.
3) Setup the different events in the View, to trigger the emits to the server as well as what should happen on receiving a socket message. ie: click a button to add an item to the page, it would emit to the server, and then you might have the client receive a message from the server and update the view so that its current.