Welcome all!
I have made a chat with websocket, the best of all is that it includes php, for this I installed this websocket (server side), in a different way.
The problem is the following, when I run the server, and I open the page from localhost/path .. there is an error in the browser,
"Uncaught ReferenceError: io is not defined" at:
"var socket = io();" from index.php, chat1.rar file
The server side appears to work, node chat.js
I've been watching for a week how to fix it,
I leave below the mentioned code.
chat.js (server side)
var express = require( 'express' );
var http = require('http');
var socket = require('socket.io');
var bodyParser = require('body-parser')
var PORT = process.env.PORT || 8080;
var fs= require('fs');
var app = express();
var server = http.createServer( app );
var io = socket.listen( server );
io.on('connection',function(socket){
var channel = 'channel-a';
socket.join(channel);
socket.on('message',function(msj){
io.sockets.in(channel).emit('message',msj,socket.id);
});
socket.on('disconnect',function(){
console.log("Desconectado : %s",socket.id);
});
});
server.listen( 1334, function() {
console.log('lisning to port 1334');
});
And index.php (client side)
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js"></script>
</head>
<body>
<div class="container">
<script type="text/javascript">
var socket = io.connect( 'http://localhost:1334' );
var socket = io();
$(function(){
$("form").submit(function(){
var mensaje = $("#msg").val();
if(mensaje=='') return false;
if(mensaje==' ') return false;
socket.emit('message',mensaje);
$("#msg").val('').focus();
return false;
});
});
socket.on('message',function(msg,id){
//output.innerHTML += '<p><strong>' + id + ': </strong>' + msg + '</p>';
$('#message').append($('<p><strong>' + id + ': </strong>' + msg + '</p>'));
//$('#message').append($('<div class="msg new-chat-message">').text(id+': '+msg));
//$('#message').append($('<div class="msg new-chat-message">').html('<span class="member-name">' + id + '</span>: ' + msg));
$('.chat-window').scrollTop($('#message').height());
//$("#message").append($('<li>').text(id+' : ' +msg));
});
socket.on('change channel',function(channel){
$("#message").html('').append($('<li>').text('system : Bienvenido al Canal '+channel+' !'));
});
</script>
<div class="col-md-12">
<div class="chat-window">
<div id="message"></div>
</div>
<div id="controls">
<form action="">
<select name="channel" id="channel">
<option value="channel-a">Channel A</option>
</select>
<div class="col-md-12">
<div class="input-group enter-chat-message">
<input type="text" id="msg" class="form-control" placeholder="Chat Message...">
<input class="input-group-addon submit-chat-message" type="submit" id="btn" value="Enviar">
</div>
</div>
</div></div>
</form>
</div></div></div></div>
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" ></script>
<script src="js/bootstrap.js"></script>
<script src="node_modules/socket.io/node_modules/socket.io-client/dist/socket.io.js"></script>
</body>
</html>
screenshot:
http://prntscr.com/ie030c
Any Help is Appreciated!
Thanks
Change this:
<script src="node_modules/socket.io/node_modules/socket.io-client/dist/socket.io.js">
To:
<script src="/socket.io/socket.io.js">
And see what happens.
Related
For a while i interest nodejs and socket.io. I know i installed nodejs and socket.io properly. I prepared a form then i got values with javascript then by sensing with ajax to my php file, then i got what a want properly. But time to making amit with socket.io i always revieve this. message
GET http://localhost/socket.io/?EIO=4&transport=polling&t=NNbUs8K 404 (Not Found) polling-xhr.js:203
GET http://localhost/socket.io/?EIO=4&transport=polling&t=NNbUsVI 404 (Not Found) polling-xhr.js:203
.
.
.
Here is my server.js
var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket.io')(http);
io.on('connection', (socket) => {
//console.log('a user connected'); //this works
socket.on('chat message', (msg) => {
console.log('message: ' + msg);
});
});
http.listen(3000, () => {
console.log('listening on *:3000');
});
Server.js works properly i tested using this console.log('a user connected'); and it works well.
Then i tried to emit real datas.
here is my html file making ajax with
<!DOCTYPE html>
<html lang="en-US">
<head>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-12">
<form method="post" action="">
<div class="form-group">
<label for="email">Email address</label>
<input type="text" class="form-control" id="email" >
</div>
<div class="form-group">
<label for="passwprd">Password</label>
<input type="password" class="form-control" id="password">
</div>
<button type="button" id="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx" crossorigin="anonymous"></script>
<script src="node_modules/socket.io/client-dist/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script>
$(function () {
$("#submit").on("click",function(){
var dataString = {
email : $("#email").val(),
password : $("#password").val(),
};
$.post("isle.php",{data:dataString},function(response){
// console.log(response);
var socket = io();
socket.emit('chat message', dataString);
return false;
},"json");
});
});
The last one is isle.php
<?php
$data=$_POST["data"];
$gonderilecek=[
"email_adres"=>$data["email"],
"sifre"=>$data["password"],
"mesaj"=>"mesajımız burada"
];
echo json_encode($gonderilecek);
I could not solve the problem any one can help me
I have followed this tutorial on YouTube: https://www.youtube.com/watch?v=zQDzNNt6xd4 for creating a chat application. I tried to save the messages but it does not work.
I also followed this tutorial for saving the chat history: https://www.youtube.com/watch?v=pigpDSOBNMc
Here is the Javascript code:
document.addEventListener('DOMContentLoaded', () => {
var socket = io.connect('http://' + document.domain + ':' + location.port);
console.log('I am connected');
//This sends the message I am now connected
socket.on('connect', () => {
socket.send("I am connected");
});
socket.on('message', data => {
const p = document.createElement('p');
const br = document.createElement('br');
p.innerHTML = data;
document.querySelector('#display-message-section').append(p);
console.log(data);
});
socket.on('some-event', data => {
console.log(data);
});
//Sending message to recipient
document.querySelector('#send_message').onclick = () => {
socket.send(document.querySelector('#user_message').value);
}
});
Here is the application file:
from flask import Flask, render_template
from flask_socketio import SocketIO, send, emit
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SECRET_KEY'] = 'm\x13\x96\xe2\xce/\xc8\x1b\xc4\x93#\xf4%\x19\x12\xca]\x9b\xc8\xe3;\xd5\x96='
socketio = SocketIO(app)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'
db = SQLAlchemy(app)
class History(db.Model):
id = db.Column('id', db.Integer, primary_key=True)
message = db.Column('message', db.String(500))
def __repr__(self):
return '<History %r>' % self.message
#socketio.on('message')
def message(p):
print('Messages: ' + p)
message = History(message=p)
db.session.add(message)
db.session.commit()
send(p, broadcast=True)
#app.route("/")
def chat():
messages = History.query.all()
return render_template('chat.html', messages=messages)
if __name__ == '__main__':
socketio.run(app, debug=True)
Here is the HTML file:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<!-- Navigation bar -->
<nav>
</nav>
<div id="main-section">
<!-- Room selection -->
<nav id="sidebar">
</nav>
<!-- Message area -->
<div id="rightside-pannel">
<!-- Display message -->
<div id="display-message-section">
</div>
<form method="POST" action="/">
<div id="input-area">
<input type="text" id="user_message" placeholder="Type here..."
autocomplete="off">
<button type="button" id="send_message">Send</button>
</form>
</div>
</div>
</div>
<!-- Get username -->
<!-- SocketIO JS -->
</body>
<!-- Custom SocketIO KS -->
<script src="//cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js" integrity="sha256-yr4fRk/GU1ehYJPAs8P4JlTgu0Hdsp4ZKrx8bDEDC3I=" crossorigin="anonymous"></script>
<script src="{{ url_for('static', filename='scripts/socketio.js') }}"></script>
</html>
I'm trying to build an app that lets me enter in information about an event and then have that pinned on a map. I'm stuck at the beginning though on actually saving the information. When I use Inspect in Chrome, it tells me it posted, but the data is blank. I'm pretty new to this kind of stuff and not sure where I'm going wrong.
The first file is the app.js where I set up the database, a simple partial schema, etc.
The second file is my dashboard.html that displays the map and the form. I was trying the onsubmit/javascript stuff which displays the data without refreshing the page, but ideally I want to be able to refresh the page and have the data still be posted somewhere.
Any help would be greatly appreciated! Thanks! :)
require('dotenv').config({ silent: false }); // Retrieve .env contents
var http = require('http'); // Basic HTTP functionality
var path = require('path'); // Parse directory paths
var express = require('express'); // Provide static routing to pages
var app = express();
var Router = require('router')
var router = Router()
var server = http.Server(app);
var port = 8080;
var app = setupExpress();
// Import mongoose module and connect the database
var mongoose = require('mongoose');
var mongoDB = 'mongodb://Username:Password#ds159180.mlab.com:59180/app-database';
mongoose.connect(mongoDB);
//Get the default connection
var db = mongoose.connection;
// Start server on port 8080
// localhost:8080
server.listen(port);
//Bind connection to error event (to get notification of connection errors)
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
//Define a schema
var Schema = mongoose.Schema;
var EventSchema = new Schema({
eventName : String,
eventType : String
});
var Event = mongoose.model('Event', EventSchema);
app.post('/dashboard', function(req, res) {
res.json(req.body); // req.body is your form data
});
app.post('/dashboard', function(req,res){
var content = new Event({
eventName : req.body.eventName,
eventType : req.body.eventType
}).save(function(err,doc){
if(err){
return handleError(err);
} else {
console.log('your form has been saved');
}
})
});
function setupExpress()
{
// Set default path for views and public
var viewsDir = path.join(__dirname, 'views');
var publicDir = path.join(__dirname, 'public');
app.use(express.static(publicDir));
// Root page is login form
app.get('/', function(req, res)
{
res.sendFile('views/index.html', { root: '.' });
});
// Once logged in, home page is dashboard
app.get('/dashboard', function(req, res)
{
res.sendFile('views/dashboard.html', { root: '.' });
});
// Redirect to error page if there's an issue
app.use(function(err, req, res, next)
{
console.log(err.stack);
res.status(err.status || 500);
res.sendFile('/views/error.html', { root: '.' });
});
return app;
}
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<!-- Web browser tab title -->
<title>App</title>
<!-- Bootstrap Core CSS -->
<link href="../vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<!-- MetisMenu CSS -->
<link href="../vendor/metisMenu/metisMenu.min.css" rel="stylesheet">
<!-- Custom CSS -->
<link href="../css/sb-admin-2.css" rel="stylesheet">
<!-- Morris Charts CSS -->
<link href="../vendor/morrisjs/morris.css" rel="stylesheet">
<!-- Custom Fonts -->
<link href="../vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<script type="text/javascript"
src="http://www.your-domain.com/easy-comment/jquery.easy-comment.min.js"></script>
<title>App Tester</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
#map {
height: 400px;
width: 100%;
}
</style>
</head>
<body>
<div id="wrapper">
<div id="page-wrapper">
<div class="row">
<div class="col-lg-8" style="margin-top: 30px">
<div class="panel panel-default">
<div class="panel-heading text-center">
<i class="fa fa-map-marker fa-3x"> Add Event</i>
</div>
<div class="panel-body">
<div class="col-lg-6">
<form id="eventForm" method="post" onsubmit="return false">
<div class="form-group">
<label for="eventName">Event Name</label>
<input type="text" class="form-control" id="eventName" placeholder="Event name">
</div>
<div class="form-group">
<label for="eventType">Type</label>
<select class="form-control" id="eventType">
<option>Study Group</option>
<option>Food</option>
<option>Meeting</option>
<option>Danger</option>
</select>
</div>
<div class="form-group">
<label for="eventLocation">Location</label>
<select class="form-control" id="eventLocation">
<option>Location 1</option>
<option>Location 2</option>
<option>Location 3</option>
</select>
</div>
<div class="form-group">
<label for="eventNotes">Event Notes</label>
<textarea class="form-control" id="eventNotes" rows="2" placeholder="Add details about your event"></textarea>
</div>
<div class="text-center">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
</div>
<div id="confirm"><div>
<script type="text/javascript">
var txt = document.getElementById("eventName");
document.getElementById("eventForm").addEventListener("submit", confirmdata);
function confirmdata(event) {
event.preventDefault();
var eventName = txt.value;
document.getElementById("confirm").innerHTML += '<p>Name: ' + eventName + '</p>';
}
</script>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
You should use body-parser to change your data post from client to json
var bodyParser = require('body-parser')
app.use(bodyParser.json())
You can get json data via req.body
I am building a simple chat app. The issue I have encounter is that users can insert scripts through the chat. Obviously this is not something I want.
A (simplified version) of my code is:
<!doctype html>
<html>
<head>
<link rel="stylesheet" href="/stylesheets/style.css"/>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.2/css/bootstrap.min.css">
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<style>
body {
padding-top: 80px;
word-wrap: break-word;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
</head>
<body ng-app="app">
<script src="/socket.io/socket.io.js"></script>
<script>
// on load of page
$(function() {
// when the client clicks SEND
$('#datasend').click(function() {
console.log('enviar data');
var message = $('#data').val();
$('#conversation').append('<b>me:</b> ' + message + '<br>');
$('#data').val('');
});
// when the client hits ENTER on their keyboard
$('#data').keypress(function(e) {
if (e.which == 13) {
$(this).blur();
$('#datasend').focus().click();
}
});
});
</script>
<script src="scripts/locate.js"></script>
<div class="container" ng-controller="userController">
<div class="row">
<div class="col-sm-12">
<div class="well">
<h3>
<span class="fa fa-comment"></span>
Chat</h3>
<div>
<div id="conversation"></div>
<input id="data" style="width:200px;"/>
<input type="button" id="datasend" value="send"/>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
For example, if an user inserts this text:
<script> alert('big problem') </script>
An alert pops up. Any ideas of how to solve this?
Thanks in advance.
you need client side code and server side code to protect XSS
as for cleint code you can use this function
function strip_tags (input, allowed) {
allowed = (((allowed || '') + '').toLowerCase().match(/<[a-z][a-z0-9]*>/g) || []).join('')
var tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi
var commentsAndPhpTags = /<!--[\s\S]*?-->|<\?(?:php)?[\s\S]*?\?>/gi
return input.replace(commentsAndPhpTags, '').replace(tags, function ($0, $1) {
return allowed.indexOf('<' + $1.toLowerCase() + '>') > -1 ? $0 : ''
})
}
usage :
var message = $('#data').val();
message= strip_tags(message, '<br><br/><br />');
$('#conversation').append('<b>me:</b> ' + message + '<br>');
also you can user php strip_tags function on server side
string strip_tags ( string $str [, string $allowable_tags ] )
more infromation
http://php.net/manual/ru/function.strip-tags.php
Thanks to what CodingWithSpike commented I managed to get to this solution:
// when the client clicks SEND
$('#datasend').click(function() {
console.log('enviar data');
var message = $('#data').val();
text = $('<span></span>').text(message);
user = $('<b> </b>').text('me: ');
div = $('<div> </div>');
div = div.append(user);
div = div.append(text);
$('#conversation').append(message);
$('#data').val('');
});
After I got to this solution I looked at what Ciprian Turco posted. It also manage to do the trick but it removed some stuff. Thats why I prefer this solution.
I've recently been teaching myself angularjs as well as node.js , from what I've learned I wrote this piece of code , but it isn't functioning , I tried logging something in the controller and it didnt log it so maybe that's a hint on what's wrong index.html code: (sorry in advance if my code is messy or anything )
<!Doctype html>
<html ng-app="Test">
<head>
<title>Test</title>
<link rel="stylesheet" type="text/css" href="bootstrap/css/bootstrap.css">
<link rel="stylesheet" type="text/css" href="style.css">
<script type="text/javascript" src="angular.min.js"></script>
<script type="text/javascript" src="angular-route.js"></script>
<script type="text/javascript">
var app= angular.module('Test' , ['ngRoute']);
app.controller('TestController' , function($scope , $http ){
$scope.submitBlog = function(){
$http.post('/blogs' , {blog : $scope.blog}).then(function(){
alert("success");
});
};
});
</script>
</head>
<body ng-app>
<h2>Blog It!</h2>
<br><br>
<div class="test" >
<input type="text" , placeholder="Username">
<br><br>
<input type="password" , placeholder="Password">
<br><br>
<button type="button" > Log In</button>
<br><br>
Not a member ? Sign Up!
</div>
<div class="blogfeed">
<h5>Feed :</h5>
<input ng-model="blog" placeholder="Your thoughts?" >
<button type="button" , ng-click="submitBlog()" , class="btn">Submit</button>
</div>
</body>
</html>
Server code :
var MongoClient = require('mongodb').MongoClient;
var ObjectId = require('mongodb').ObjectId;
var express = require('express');
var bodyParser = require('body-parser');
var bcrypt = require('bcryptjs');
var app = express();
var db = null;
MongoClient.connect("mongodb://localhost:27017/test" , function(err,dbconn){
if(!err){
console.log("We are connected");
db= dbconn;
}
});
app.use(express.static('public'));
app.use(bodyParser.json());
app.post('/blogs' , function(res,req,next){
db.collection('blogs' , function(err , blogsCollection){
var newBlog= {
text: req.body.blog
};
blogsCollection.insert(newBlog , {w:1} , function(err){
return res.send();
});
});
});
app.listen(3000, function(){
console.log('Example app listening on port 3000');
});
You are creating a controller that is never used.
you have to bind your controller to a dom element with the ng-controller directive
you could append it to the body tag like so
<body ng-app ng-controller="TestController" >
Check this. You've created a ng-app i.e Testand a controller TestController. But you've never used it. If you want to use the controller for the whole body i.e one controller for the whole application then use ng-controller="TestController" on the body tag. Similarly do it for other elements if you want the scope of the controller limited to the children of a particular element.
<!Doctype html>
<html ng-app="Test">
<head>
<title>Test</title>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.5/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module('Test', []);
app.controller('TestController', function($scope, $http) {
console.log('In the controller');
$scope.submitBlog = function() {
$http.post('/blogs', {
blog: $scope.blog
}).then(function() {
alert("success");
});
};
});
</script>
</head>
<body ng-controller="TestController">
<h2>Blog It!</h2>
<br>
<br>
<div class="test">
<input type="text" , placeholder="Username">
<br>
<br>
<input type="password" , placeholder="Password">
<br>
<br>
<button type="button">Log In</button>
<br>
<br>
Not a member ? Sign Up!
</div>
<div class="blogfeed">
<h5>Feed :</h5>
<input ng-model="blog" placeholder="Your thoughts?">
<button type="button" , ng-click="submitBlog()" , class="btn">Submit</button>
</div>
</body>
</html>