How should the chat application example (described on https://socket.io/get-started/chat/) look if I wanted the client script that currently exists in the index.html file, to exist in a separate client.js file? Note: In this example tutorial, I'm at the part where I'm trying to get a user connected to appear when refreshing the web page, but this is not working correctly.
I've tried including <script src="client.js"></script> in the head section of my index.html file, and then
const io = require('socket.io-client');
var socket = io();
in my client.js file, but it does not work. When I run node server.js, the chat application design displays on the web page correctly, and I show the listening on *:3000 text in the terminal, but not the a user connected text which should appear when I refresh the web page.
My server.js, index.html, and client.js files are all in the top level of the directory, and are as follows:
server.js
var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket.io')(http);
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html'); // Based on some research, I feel that the problem might
// be here, where I'm sending just a file, not a directory?..
});
io.on('connection', (socket) => {
console.log('a user connected');
});
http.listen(3000, () => {
console.log('listening on *:3000');
});
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Chat Application</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font: 13px Helvetica, Arial; }
form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
form input { border: 0; padding: 10px; width: 90%; margin-right: 0.5%; }
form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
#messages { list-style-type: none; margin: 0; padding: 0; }
#messages li { padding: 5px 10px; }
#messages li:nth-child(odd) { background: #eee; }
</style>
<script src="client.js"></script>
</head>
<body>
<ul id="messages"></ul>
<form action="">
<input id="m" autocomplete="off" /><button>Send</button>
</form>
</body>
</html>
client.js
// I am also unsure if the following is correct...
const io = require('socket.io-client');
var socket = io();
This is an old question but still an issue with the socket.io example code. I was able to figure it out. The issue is that the file-system works differently when running whatever server (including localhost).
In short, to resolve this issue, in index.js (or what is called server.js in OP's question), replace:
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
with
app.use(express.static(__dirname));
app.get('/', (req, res) => {
});
(of course feel free to fill the app.get function later if needed.
Related
I have a simple login form app in node.js. I am able to display the login form and enter login data but my POST request to capture the login data doesn't work, I get POST http://localhost:3000/client 404 (Not Found) error at the js console. I think I am coding the path wrong in the post request. My HTML code for the login form is in the client.html file and my js code is in the server.js file. I am providing both.
Here is my client.html file:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" content="width=device-width, initial-scale=1">
<title>Havuzlu Site main page</title>
<style>
/* Use havuzlusite picture as full page background. */
html {
background-image: url("/havuzlusite-img.jpg");
background-repeat: no-repeat;
background-position: center center;
background-attachment: fixed;
background-size: cover;
}
h1 {
color: black;
text-align: center;
}
/* Set general style for the button class. */
.button {
border: none;
color: white;
text-decoration: none;
display: inline-block;
font-size: 16px;
cursor: pointer;
}
/* Create classes for main page buttons. */
.bldgnews-btn {background-color: aqua; margin-left: 39%;}
.bldgmngmt-btn {background-color: blue; margin: center;}
.login-btn {background-color: blueviolet; margin-right: 39%;}
/* The popup login form - hidden by default */
.login-form {
display: none;
position: fixed;
bottom: 0;
right: 15px;
border: 3px solid #f1f1f1;
z-index: 9;
max-width: 300px;
padding: 10px;
background-color: white;
}
/* Set styling for the input fields of the login-form. */
.login-form input[type=text], .login-form input[type=password] {
width: 100%;
padding: 15px;
margin: 5px 0 22px 0;
border: none;
background: #f1f1f1;
}
/* Set additional styling When the input fields get focus (when they are clicked). */
.login-form input[type=text]:focus, .login-form input[type=password]:focus {
background-color: #ddd;
outline: none;
}
/* Set styling for the login button. */
.login-form .login-btn {
background-color: #04AA6D;
color: white;
padding: 16px 20px;
border: none;
cursor: pointer;
width: 100%;
margin-bottom:10px;
opacity: 0.8;
}
/* Add a red background color to the cancel button */
.login-form .cancel-btn {
background-color: red;
}
/* Add some hover effects to buttons */
.login-form .btn:hover, .open-button:hover {
opacity: 1;
}
</style>
</head>
<body>
<! Create main page. >
<h1>Havuzlu siteye hoş geldiniz</h1>
<button class="bldgnews-btn" type="submit">Site haberleri</button>
<button class="bldgmngmt-btn" type="submit">Site yönetimi</button>
<button class="login-btn" onclick="openLoginForm()">Aidat takibi</button>
<! Create login form. >
<form class="login-form" id="loginForm" action="http://localhost:3000/client"
method="POST">
<h1>Kullanıcı girişi</h1>
<label for="isim"><b>isim</b></label> >
<input type="text" placeholder="İlk ve soy isim giriniz" id="isim" name="isim"
required>
<label for="sifre"><b>şifre</b></label> >
<input type="password" placeholder="Şifre giriniz" id="sifre" name="sifre" required>
<button type="submit" class="login-btn">Giriş</button> >
<button type="button" class="cancel-btn" onclick="close-Form()"> Kapat</button>
</form>
<script>
function openLoginForm() {
document.getElementById("loginForm").style.display = "block";
}
function closeForm() {
document.getElementById("loginForm").style.display = "none";
}
</script>
<script>src="/server.js"</script>
</body>
</html>
Here is my server.js file:
//import express, { static, urlencoded } from "express";
const express = require('express'); // Import Express package
const app = express(); // Create an Express app variable so that we can use Express in
anywhere.
const router = express.Router();
// add router in express app
app.use("/",router);
//import path from "path";
const path = require('path');
// Import body-parser module to parse incoming requests
const bodyParser = require('body-parser');
//import cors from "cors";
const cors = require('cors');
const port = 3000; //Set port to 3000.
// Below, we use the modules that we imported.
app.use(express.json() ); // use Express module body-parser to parse JSON-encoded request
bodies
app.use(express.urlencoded({extended: true})); // use Express module body-parser to parse URL-
encoded request bodies
app.use(cors());
// Send the local image file to be used as app homepage background, to the client.
app.get('/havuzlusite-img.jpg', function(req, res) {
res.sendFile("D:/Behrans-files/Web-projects/havuzlusite/havuzlusite-img.jpg");
});
// Send html code for app homepage and login page, to the client.
app.get('/', function(req, res) {
res.sendFile("D:/Behrans-files/Web-projects/havuzlusite/client.html");
});
//Route for login. When the user clicks Login button, we will post the //request to server and
//get the response.
//router.post('/client', (req, res) => {
app.post('http://localhost:3000/client', (req, res) =>{
console.log(req.body);
console.log(req.body.sifre);
res.end("yes");
});
app.listen(port, () => {
console.log("server is running at http://127.0.0.1:", port);
});
app.post should only take the path, not the entire URL (just like you did with `app.get):
app.post('/client', (req, res) =>{
// Here^
console.log(req.body);
console.log(req.body.sifre);
res.end("yes");
});
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<link rel="stylesheet" href="css/animate.css">
<link rel="stylesheet" href="css/style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" >
$(document).ready(function()
{
$("#notificationLink").click(function()
{
$("#notificationContainer").fadeToggle(300);
$("#notification_count").fadeOut("slow");
return false;
});
//Document Click
$(document).click(function()
{
$("#notificationContainer").hide();
});
//Popup Click
$("#notificationContainer").click(function()
{
return false
});
});
</script>
<style>
body{background-color:#dedede;font-family:arial}
#nav{list-style:none;margin: 0px;
padding: 0px;}
#nav li {
float: left;
margin-right: 20px;
font-size: 14px;
font-weight:bold;
}
#nav li a{color:#333333;text-decoration:none}
#nav li a:hover{color:#006699;text-decoration:none}
#notification_li{position:relative}
#notificationContainer {
background-color: #fff;
border: 1px solid rgba(100, 100, 100, .4);
-webkit-box-shadow: 0 3px 8px rgba(0, 0, 0, .25);
overflow: visible;
position: absolute;
top: 30px;
margin-left: -170px;
width: 400px;
z-index: -1;
display: none;
}
#notificationsBody {
padding: 33px 0px 0px 0px !important;
min-height:300px;
}
#notification_count {
padding: 3px 7px 3px 7px;
background: #cc0000;
color: #ffffff;
font-weight: bold;
margin-left: 100px;
border-radius: 9px;
position: absolute;
margin-top: 0px;
font-size: 11px;
}
</style>
</head>
<body >
<div style="margin:0 auto;width:900px; margin-top: 30px;">
<ul id="nav">
<li id="notification_li">
<span id="notification_count">5</span>
Notifications
<div id="notificationContainer">
<div id="notificationTitle">Notifications</div>
<div id="notificationsBody" class="notifications">
</div>
</div>
</li>
</ul>
</div>
</body>
</html>
I am working on a page that has getting the notification from the server. I just create a button and a small div for showing notification number. I want to make that div was getting the notification from the server when the server push to that div.
How can I get the push notification from the server. I want the client side code for receiving notification from sever. I just using another system and node js is the server.
Thank you.
You can achieve it using node js. Following is a working code example.
Node js : index.js
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get("/", function (req, res) {
res.sendFile("index.html", {root: __dirname});
});
io.on("connection", function (socket) {
socket.on("notify", function (notification_request) {
io.emit('notify', JSON.stringify(notification_request));
});
});
http.listen(3000, function () {
console.log('listenting on 3000');
});
your frontent index.html before </body>
<script>
var socket = io();
$('button').click(function () { //notify event triggered
socket.emit('notify', {notification-1: "message1", notification-2: "message2", notification-3: "message3"});
return false;
});
socket.on('notify', function (notification) {
var notifications = JSON.parse(notification); //process notication array
$('#notification-div').append(notifications); //display the notification here which is going to be reflected for all clients
});
</script>
Run your index.js file on terminal or CLI to activate server. And Don't forget to install following node modules
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
Use http request object on javascript and get the response from it then append it to your html. Or you can use jquery ajax also.
The Best practice for notification mechanism in Node js is to use socket.io. It's really simple & easy to handle & best for real time updation.
Check out this link : -
http://socket.io/
So I'm trying to connect to my server which I've created with Node.js,Socket.io, and Express externally from the outside internet, not on my local network.
Here is my code:
Server:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
socket.on('chat message', function(msg){
io.emit('chat message', msg);
});
});
http.listen(3000,function(){
console.log('listening on *:3000');
});
Client:
<!doctype html>
<html>
<head>
<title>Socket.IO chat</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font: 13px Helvetica, Arial; }
form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
#messages { list-style-type: none; margin: 0; padding: 0; }
#messages li { padding: 5px 10px; }
#messages li:nth-child(odd) { background: #eee; }
</style>
</head>
<body>
<ul id="messages"></ul>
<form action="">
<input id="m" autocomplete="off" /><button>Send</button>
</form>
<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script>
var socket = io();
$('form').submit(function(){
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
socket.on('chat message', function(msg){
$('#messages').append($('<li>').text(msg));
});
</script>
</body>
I have port forwarded port 3000. http://localhost:3000/ works, so does connecting on other computers on the same network, but I got my external IP: 12.888.999.12(random IP). I also have my port 3000. When I connect in google chrome at http://12.888.999.12:3000 does not work.
When you say external ip does that mean you have purchased a cloud server somewhere or its in the intranet.. Which OS are you using? is the port 3000 open on the server machine?
eg. if its a windows machine you need to go to Windows Firewall with Advanced Security and open the inbound port for TCP access
If you have done that then try this ::
http.listen(3000, '0.0.0.0', function() {
console.log('Listening to port: ' + 3000);
});
and then try to access with http://12.888.999.12:3000
The issue is likely your routeur handling the query (because it know the ip belong to him) instead of fowarding it back to your server (even with port fowarding done correctly).
Side note: I had routeurs in the past that handled ANY kind of traffic (from whatever port) and always returned an 500 HTTP error.
So I would suggest you to use a random website to test if your port is reachable from the internet then continue testing your server from your own computer using localhost.
If it is not then it could be two things :
Your port mapping from your router is wrong
You must use your LAN IP in the router configuration.
The source port (if you can provide one) should be the port you want to use from the internet, and the destination port should be the port from your server (here 3000)
Tests you did with computers on your lan only confirm that the firewall of your server computer is currectly configured, it didn't test anything on the router side.
Your ISP may block incoming traffic (it is unlikely in your case because if it does it will on standards port such as 80, 21, 8080, 443)
I am trying to write a web chat client in socket.io, but first I need to get my server talking to the website on localhost.
I am getting the 'listening' message, but nothing happens when I open up localhost in a new tab to say that a user connected. Apache server is running, so is express, so is node.js.
Here is my index.js, which serves up my index.html:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');});
io.on('connection', function(socket){
console.log('a user connected');});
http.listen(3000, function(){
console.log('listening on *:3000');});
and here is my index.html:
<!DOCTYPE html PUBLIC>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css" />
<title>Web chat practice</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font: 13px Helvetica, Arial; }
form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
#messages { list-style-type: none; margin: 0; padding: 0; }
#messages li { padding: 5px 10px; }
#messages li:nth-child(odd) { background: #eee; }
</style>
</head>
<body>
Here will be the web chat:
<ul id="messages"></ul>
<form action="">
<input id="m" autocomplete="off" /><button>Send</button>
</form>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.();
</script>
</body>
</html>
I could also use some general direction in the MEAN stack.
This line of code in index.html creates an error:
var socket = io.();
The code should be:
var socket = io();
This will connect to your Express server/socket.io (if the web page is being served by that Express server). That should generate the 'a user connected' message in your server console, but it won't do anything else because your web page doesn't do anything else with socket.io.
In addition, your server code looks suspect. I'd suggest you take the Express 4 example right from here: http://socket.io/docs/#using-with-the-express-framework.
I do not understand why you mention an Apache server as that is not typically part of an Express/socket.io implementation.
I have followed a tutorial for socket.io chat:
https://www.youtube.com/watch?v=pNKNYLv2BpQ
In the tutorial video it works fine however mine does not work at all. The messages do not seem to be sent or received by either the server or the client
This is my app.js run on the server side with node
var express = require('express'),
app = express(),
server = require('http').createServer(app),
io = require('socket.io').listen(server);
server.listen(3000);
app.get('/', function(req, res) {
res.sendfile(__dirname + '/index.html');
});
io.sockets.on('connection', function(socket) {
socket.on('send message', function(data) {
io.sockets.emit('new message', data);
});
});
This is my index.html client
<html>
<head>
<title>Chat with socket.io and node.js</title>
<style>
#chat
{
height: 500px;
}
</style>
</head>
<body>
<div id="chat"></div>
<form id="send-message">
<input size="35" id="message"></input>
<input type="submit"></input>
</form>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
jQuery(function($) {
var socket = io.connect();
var $messageForm = $('#send-message');
var $messageBox = $('#message');
var $chat $('#chat');
$messageForm.submit(function(e) {
e.preventDefault();
socket.emit('send message', $messageBox.val());
$messageBox.val('');
});
socket.on('new message', function(data) {
$chat.append(data + "<br/>");
});
});
</script>
I suppose it is a simple error that I have overlooked but I'm stumped at the moment, any ideas ??? Also if you require additional information please say so :)
create one index.html file
index.html
<!doctype html>
<html>
<head>
<title>Socket.IO chat</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font: 13px Helvetica, Arial; }
form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
#messages { list-style-type: none; margin: 0; padding: 0; }
#messages li { padding: 5px 10px; }
#messages li:nth-child(odd) { background: #eee; }
</style>
</head>
<body>
<ul id="messages"></ul>
<form action="">
<input id="m" autocomplete="off" /><button>Send</button>
</form>
</body>
</html>
<script>
var socket = io();
$('form').submit(function(){
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
socket.on('chat message', function(msg){
$('#messages').append($('<li>').text(msg));
});
</script>
index.js
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendfile('index.html');
});
io.on('connection', function(socket){
console.log('a user connected');
socket.on('chat message', function(msg){
console.log('message: ' + msg);
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
For more information click here