I have a nodejs code given with html code, I want to show a sweet alert on client side,after process a function in nodejs?.
var express = require('express');
var router = express.Router();
const Swal = require('sweetalert2');
router.post('/add', function(req, res, next) {
Swal('Hello world!');
});
<!DOCTYPE html>
<html lang="pt_br">
<head>
</head>
<body>
<h1 class="text-center title-1"> Cad </h1>
<form action="/add" method="post">
<input type="submit" value="Save"/>
</form>
</body>
</html>
Here's the only way you can show a popup swal
var express = require('express');
var router = express.Router();
router.post('/add', function(req, res, next) {
res.json("Hello world!")
});
<!DOCTYPE html>
<html lang="pt_br">
<head>
</head>
<body>
<h1 class="text-center title-1"> Cad </h1>
<form id="form" action="#" method="post">
<input type="submit" value="Save"/>
</form>
</body>
</html>
<script>
//import JQuery from script
//import swal script
$("#form").on("submit", function(e){
e.preventDefault();
$.ajax({
url: "/add",
method: "post"
}).done(d=>{
swal(e.responseJSON);
});
})
</script>
Here you can do using EJS
var express = require('express');
var router = express.Router();
router.post('/add', function(req, res, next) {
res.status(201).render('new', { isAdded : true } );
});
In HTML side
<% if (isAdded) { %>
<script>
Swal.fire(
'Good job!',
'Data saved',
'success'
)
</script>
<% } %>
In order to deal with this, you can use query parameters.
So, Here is what you can do
On the server
var express = require('express');
var router = express.Router();
router.post('/login', (req, res)=>{
res.redirect("/login?success=true&message=Logged In Successfully")
});
On the Client-Side (EJS)
<script>
var urlParams = new URLSearchParams(window.location.search);
if(urlParams.has('success') && urlParams.get('success')){
swal({
title: "Failed",
text: `${message}`,
icon: "error",
button: "Okay",
}).then(()=>{
console.log(window.location.hostname)
window.location.replace(window.location.origin + '/login');
})
}
This will simply popup swal. And you can toggle the value of success to render error and success messages.
Related
I'm trying to build a database using mongodb where it will render to an html page using ejs. Backend is node/express.
How do I link the button to an addeventlistener. EJS documentation is limited and I've read other posts that says ejs only renders html but no other functionality.
Eventually, I would like to use an async/await to link the js with the backend.
Here is my ejs:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<h1>The Beautiful Game</h1>
<form action="/players" method="POST">
<input type="text" placeholder="name" name="name" />
<input type="text" placeholder="club" name="club" />
<button type="submit" class='submitButton'>Submit</button>
</form>
<h2>Players</h2>
<ul class="players">
<% for (var i = 0; i < players.length; i++) {%>
<li class="players">
<span><%= players[i].name %></span>:
<span><%= players[i].club %></span>
<button class="dataDeleteNameButton" data-id="<%=players[i]._id%>">Delete</button> <!-- linking this button -->
</li>
<% } %>
</ul>
<script type="text/javascript" src="js/main.js"></script>
</body>
</html>
Here is my js:
document
.querySelector("dataDeleteNameButton")
.addEventListener("click", deleteEntry);
async function deleteEntry() {
console.log("Button is working!");
}
Here is the server, if needed:
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
const cors = require("cors");
const MongoClient = require("mongodb").MongoClient;
const PORT = process.env.PORT || 8000;
app.use(cors());
const username = "hidden";
const password = "hidden";
const connectionString = `mongodb+srv://${username}:${password}#cluster0.7k2ww.mongodb.net/myFirstDatabase?retryWrites=true&w=majority`;
MongoClient.connect(connectionString, { useUnifiedTopology: true })
.then((client) => {
console.log("Connected to database");
const db = client.db("soccer-players");
const playerCollection = db.collection("players");
app.set("view engine", "ejs");
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(express.static("public"));
app.get("/", (req, res) => {
db.collection("players")
.find()
.toArray()
.then((result) => {
res.render("index.ejs", { players: result });
})
.catch((error) => console.error(error));
});
app.get("/api/players", (req, res) => {
db.collection("players")
.find()
.toArray((err, arr) => {
res.json(arr);
});
});
app.post("/players", (req, res) => {
playerCollection
.insertOne(req.body)
.then((result) => {
res.redirect("/");
})
.catch((error) => console.error(error));
console.log(req.body);
});
app.delete("/", (req, res) => {
// playerCollection.deleteOne() <--
// let findID =
});
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
})
.catch((error) => console.error(error));
Picture of what it looks like:
This is my script tag path: ../client-side-folder/js-folder/main.js
Directory:
main-folder
+--client-side-folder
+----js-folder
+------main.js
+--views-folder
+----index.ejs
You can just do onclick="myFunction(theIdOfTheButtonHere)"
Here is an example:
https://www.w3schools.com/jsref/event_onclick.asp
I want to combine a weather API with a form where you fill in your mood into 1 app:
a form where you fill in you city (so you get the weather) and where you fill in your mood of that day.
In my server.js file I have two GET and two POST functions.
However, I think I can only use res.render('index',...) once.
How to combine the two GET functions into 1 working function?
server.js file
const express = require('express')
const app = express()
app.use(express.static('./public'))
// --> npm install body-parser
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// --> npm install ejs
app.set('view engine', 'ejs');
// --> npm install request
// --> npm install request-promise
const request = require('request-promise');
// --> npm install mongoose
const mongoose = require('mongoose');
mongoose.connect('mongodb+srv://MONGO_HOST/test?retryWrites=true&w=majority');
// apiKey
const apiKey = 'XXX';
// database weather
var citySchema = new mongoose.Schema({
city: String
});
var cityModel = mongoose.model('City', citySchema);
// database mood
var moodSchema = new mongoose.Schema({
name: String,
description: String,
date: String
});
var moodModel = mongoose.model('Mood', moodSchema);
// function which gets a list of moods in the database
async function getDiary(moods) {
var diary_data = [];
for (var mood_obj of moods) {
var name = mood_obj.name;
var description = mood_obj.description;
var date = mood_obj.date;
var diary = {
name : name, // variable declared above
description : description, // variable declared above
date : date // variable declared above
};
diary_data.push(diary);
}
return diary_data;
};
// GET route mood
app.get('/', function (req, res) {
moodModel.find({}, function(err, moods){
console.log(moods);
getDiary(moods).then(function(results){
var diary_data = {diary_data: results};
res.render('index', diary_data);
})
});
})
// function which gets a list of cities in the database
async function getWeather(cities) {
var weather_data = [];
for (var city_obj of cities) {
var city = city_obj.name;
var url = `http://api.openweathermap.org/data/2.5/weather?q=${city}&units=imperial&appid=${apiKey}`;
var response_body = await request(url);
var weather_json = JSON.parse(response_body);
var weather = {
city : city, // variable declared in this document
temperature: weather_json.main.temp, // variable from API data
description : weather_json.weather[0].description, // variable from API data
icon : weather_json.weather[0].icon, // variable from API data
};
weather_data.push(weather);
}
return weather_data;
};
// GET route weather
app.get('/', function (req, res) {
cityModel.find({}, function(err, cities){
console.log(cities);
getWeather(cities).then(function(results){
var weather_data = {weather_data: results};
res.render('index', weather_data);
})
});
})
// POST route mood
app.post('/', function(req, res) {
var newMood = new moodModel({
name: req.body.mood_name,
description: req.body.mood_description,
date: req.body.mood_date
});
newMood.save();
res.redirect('/');
})
// POST route weather
app.post('/', function(req, res) {
var newCity = new cityModel({city: req.body.city_name});
newCity.save();
res.redirect('/');
});
// setup port
const port = 3000;
app.listen(port, function() {
console.log(`server is listening on port ${port}`);
})
index.ejs file
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Test</title>
<link rel="stylesheet" type="text/css" href="/css/style.css">
<link href='https://fonts.googleapis.com/css?family=Open+Sans:300' rel='stylesheet' type='text/css'>
</head>
<body>
<div class="container">
<% for (diary of diary_data) { %>
<div class="moodBox">
<span class="title"><%= diary.name %></span>
<br>
<span class="title"><%= diary.description %></span>
<br>
</div>
<% } %>
<% for (weather of weather_data) { %>
<div class="weatherBox">
<span class="title"><%= weather.city %></span>
<br>
<span class="subtitle"><%= weather.temperature %></span>
<br> <%= weather.description %>
</div>
<% } %>
<fieldset>
<form method="post" action="/">
<div>
<label for="mood_name">mood name</label>
<input type="text" name="mood_name" required>
</div>
<div>
<label for="mood_description">mood description</label>
<input type="text" name="mood_description" required>
</div>
<div>
<input type="date" name="mood_date">
<div id="theDate"></div>
</div>
<div>
<label for="city_name">City name</label>
<input type="text" name="city_name">
</div>
<button type="submit">Submit</button>
</form>
</fieldset>
</div>
<script src="/extra.js"></script>
</body>
</html>
I am trying to show a confirmation message before user deletes anything. I've tried following various related sources that I found in internet, but couldn't get them to work. I am using EJS template and Express 4.
app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
var flash = require('connect-flash');
var session = require('express-session');
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use('/js', express.static(__dirname + '/node_modules/bootstrap/dist/js')); // redirect bootstrap JS
app.use('/css', express.static(__dirname + '/node_modules/bootstrap/dist/css')); // redirect CSS bootstrap
// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(cookieParser());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(require('stylus').middleware(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));
app.use(session({ secret: 'zxcv' })); // session secret
app.use(flash()); // use connect-flash for flash messages stored in session
app.use('/', routes);
app.use('/users', users);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function (err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function (err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
app.listen(8000);
module.exports = app;
index.js
var express = require('express');
var router = express.Router();
var searchModule = require('../crud_module/search.js');
var updateModule = require('../crud_module/update.js');
var deleteModule = require('../crud_module/delete.js');
/* GET home page. */
router.get('/', function (req, res) {
res.render('index', { title: '' });
});
router.post('/search-results', function (req, res) {
searchModule.search(req.body, function (data) {
res.render('index', { title: '', results: data });
});
});
router.post('/edit-data', function (req, res) {
searchModule.searchById(req.body, function (data) {
res.render('edit', { title: '', results: data });
});
});
router.post('/save-changes', function (req, res) {
if (req.body.change == "update") {
updateModule.saveChanges(req.body, function (err) {
if (err) {
res.render('edit', { message: req.flash('Error', 'Error Occured') });
} else {
//req.flash('success', 'Your name was updated');
res.render('edit', { message: req.flash('success', 'Data was updated')) });
}
res.redirect('/edit-data');
});
}
if (req.body.change == "delete") {
deleteModule.deleteRecord(req.body, function (data) {
res.render('edit', { title: 'Volume Tracker', confirmation: data });
});
}
});
module.exports = router;
edit.ejs
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
<link href="node_modules/popups/css/popupS.min.css" rel="stylesheet" />
<script type="text/javascript" src="https://gc.kis.scr.kaspersky-labs.com/5B1FA715-F8FF-784F-A4C9-0D867337CB3D/main.js" charset="UTF-8"></script><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="node_modules/elasticsearch/src/elasticsearch.angular.js"></script>
<script src="node_modules/popups/dist/popupS.min.js"></script>
<script language="javascript">
</script>
<style type="text/css">
</style>
</head>
<body>
<br>
<form action='/save-changes' method='post'>
<div class="container">
<% if(locals.results) { %>
<table class="table table-bordered table-hover table-condensed">
<tr>
<th bgcolor="silver">Term Key</th>
<td>
<input name="termKey" value= "<%= results[0]._source.termkey %>" style="border:none; width:100%"/>
</td>
</tr>
<tr>
<th bgcolor="silver">Active</th>
<td>
<input name="active" value= "<%= results[0]._source.active %>" style="border:none; width:100%"/>
</td>
</tr>
<tr>
<th bgcolor="silver">Term Description</th>
<td>
<input name="termDescription" value= "<%= results[0]._source.termdescription %>" style="border:none; width:100%"/>
</td>
</tr>
</table>
<div align="center">
<button type="submit" class="btn btn-info" name="change" value="update"> Save Changes </button>
<button type="submit" class="btn btn-danger" name="change" value="delete"> Delete Record </button>
</div>
<% } %>
</form>
<br>
</div>
</body>
</html>
Here, when the user will click on the delete button, a confirmation message will be shown (here--> in index.js, I first tried showing confirmation message after user updates anything; which didn't work either). But whenever I try to include this:
<% if (message.length > 0) { %>
<div class="alert alert-danger"><%= message %></div>
<% } %>
in edit.ejs , I get error:
ReferenceError:
92| </form>
93| <br>
>> 94| <% if (message.length > 0) { %>
95| <div class="alert alert-danger"><%= message %></div>
96| <% } %>
message is not defined
at eval (eval at <anonymous> (\ElasticSearch\ES\VolumeTracker\VolumeTracker\node_modules\ejs\lib\ejs.js:495:12), <anonymous>:41:12)
at Template.compile.returnedFn (\ElasticSearch\ES\VolumeTracker\VolumeTracker\node_modules\ejs\lib\ejs.js:524:17)
at View.exports.renderFile [as engine] (\ElasticSearch\ES\VolumeTracker\VolumeTracker\node_modules\ejs\lib\ejs.js:378:31)
at View.render (\ElasticSearch\ES\VolumeTracker\VolumeTracker\node_modules\express\lib\view.js:76:8)
at Function.app.render (\ElasticSearch\ES\VolumeTracker\VolumeTracker\node_modules\express\lib\application.js:527:10)
at ServerResponse.res.render (\ElasticSearch\ES\VolumeTracker\VolumeTracker\node_modules\express\lib\response.js:900:7)
at \ElasticSearch\ES\VolumeTracker\VolumeTracker\routes\index.js:22:13
at \ElasticSearch\ES\VolumeTracker\VolumeTracker\crud_module\search.js:45:9
at tryCallOne (\ElasticSearch\ES\VolumeTracker\VolumeTracker\node_modules\elasticsearch\node_modules\promise\lib\core.js:37:12)
at \ElasticSearch\ES\VolumeTracker\VolumeTracker\node_modules\elasticsearch\node_modules\promise\lib\core.js:123:15
I have a simpler solution; as an example: after a succesful registration of a new user in the file routes/users.js:
req.flash('success_msg', 'You are registered and can now log in');
res.redirect('login');
In a file views/partials/_messages.ejs:
<% if (success_msg != '') { %>
<div class="alert alert__success"><%= success_msg %></div>
<% } %>
And in views/login.ejs include:
<% include ./partials/_messages %>
No other JavaScript needed!
I am posting here answer to my own question, in case anyone needs the same thing. To pass flash message to view, in your app.js ensure the following is present (note I am using ejs template for view) :
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var app = express();
var flash = require('connect-flash');
var session = require('express-session');
app.use(cookieParser());
app.use(session({ secret: 'zxcv' })); // session secret
app.use(flash()); // use connect-flash for flash messages stored in session
in your index.js
router.post('/edit', function (req, res) {
if (req.body.change == "update") { //if update btn is clicked
updateModule.saveChanges(req.body, function (err) { //call update module
if (err) {
//if error
req.flash("msg","Error Occured");
res.locals.messages = req.flash();
res.render('edit', { title: 'myApp'});
} else {
//on success
req.flash("msg", "Data updated successfully");
res.locals.messages = req.flash();
res.render('index', { 'title': 'myApp'});
}
});
}
});
and here is my view: for editing--> edit.ejs
<body>
<form action='/edit' method='post'>
<!--your data-->
<script language="javascript">
function UpdateConfirm() {
var userPreference;
if (confirm("Do you want to save changes?") == true) {
return true;}
else {
return false;}
}
</script>
<button type="submit" class="btn btn-info" name="change" value="update" onClick= "<%- "return UpdateConfirm()" %>" > Save Changes </button>
</form>
</body>
Here, if you click on the button, it will first popup a confirmation alert box (will call UpdateConfirm()), and if you click yes then it will submit the form.
Now, after updating I am passing flash message from my index.js. The view where you want to show the flash message, put this:
<% if (locals.messages) { %>
<script language="javascript">
alert("<%= messages.msg %>");
</script>
<% } %>
It will show the message in an alert box.
P.S: You have to install these npm packages: cookie-parser,connect-flash and connect-flash
I'm working with PassportJS and javascript to login and signup a new user. Then, after the signup part (which works perfectly), when I try to login I receive the page "Cannot POST /login". Can you help me understanding which is the error? Here is my code:
'use strict';
var express = require('express');
var router = express.Router();
var middleware = require('../middleware');
var rootUrl = require("../../config").url;
//supported methods
router.all('/', middleware.supportedMethods('GET, OPTIONS'));
// As with any middleware it is quintessential to call next()
// if the user is authenticated
var isAuthenticated = function (req, res, next) {
if (req.isAuthenticated())
return next();
res.redirect('/');
};
router.get('/library', isAuthenticated, function(req, res){
res.render('library', { user: req.user });
});
module.exports = function(passport){
/* GET login page. */
router.get('/', function(req, res) {
// Display the Login page with any flash message, if any
res.render('library');
});
/* Handle Login POST */
router.post('/users', passport.authenticate('users', {
successRedirect: '/library',
failureRedirect: '/'
}));
/* GET Registration Page */
router.get('/signup', function(req, res){
res.render('login');
});
/* Handle Registration POST */
router.post('/signup', passport.authenticate('signup', {
successRedirect: '/login',
failureRedirect: '/signup'
}));
return router;
};
And in the part of the dust (where I ask for the POST), I have the following code:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1.0">
<title>Login</title>
<link rel="stylesheet" href="css/standardize.css">
<link rel="stylesheet" href="css/base.css">
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
</head>
<body class="body login">
<div class="vertical-align-wrapper">
<div class="vertical-align-box">
<h1 class="slogan">We make your <i class="fa fa-heart beats pulse" style="color:#3b7cff;"></i> beats.</h1>
<div class="form-login-wrapper">
<form action="/login" method="POST" class="form-login">
<input class="form-control form-stacked" name="userName" placeholder="Username" type="text">
<input class="form-control form-stacked last" name="password" placeholder="Password" type="password">
<input class="btn btn-beats btn-block btn-stacked" value="Tune in" type="submit" id="submit">
</form>
<p>Don't have an account? <strong>sign up</strong> now! </p>
</div>
</div>
</div>
<h1 class="fat blue-glow bottom-right">Atelier<span class="pulse" style="display:inline-block;">Beats.</span></h1>
</body>
</html>
And here is my login code:
/** #module users/router */
'use strict';
var express = require('express');
var router = express.Router();
var middleware = require('../middleware');
var rootUrl = require("../../config").url;
//supported methods
router.all('/', middleware.supportedMethods('GET, OPTIONS'));
//list users
router.get('/', function(req, res, next) {
res.render('login');
});
/** router for /users */
module.exports = router;
Solution find:
/**
* Created by test on 12.12.14.
*/
var express = require('express');
var router = express.Router();
var middleware = require('../middleware');
var mongoose = require('mongoose');
var ObjectId = mongoose.Types.ObjectId;
var User = mongoose.model('User');
var config = require("../../config");
var session;
router.all('/', middleware.supportedMethods('GET, POST'));
router.get('/', function(req, res, next) {
res.render('login');
});
router.post('/', function (req, res) {
var post = req.body;
var query = User.where({userName : post.username});
query.findOne(function(err, user){
if (err) { return err}
if (user) {
user.isValidPassword(post.password, function(n, isMatch){
if(isMatch) {
req.session.user_id = user._id;
res.redirect('/library?' + user._id);
} else{
res.redirect('/login');
}
});
}else{
res.redirect('/login');
}
});
});
module.exports = router;
I have a group chat app. When client login with his email and password, he would be directed to chat page with his name on top and he would able to chat with online user.How can my app. identify from which user message was sent. One possibility is to send socket.id along with message to server for identifying user but socket.id get changed on refreshing the page.
login.html
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="/loginstyle.css" />
</head>
<body>
<form class="css" method="post" action="http://192.168.1.3:9373/valid" >
<fieldset >
<input type="text" name="email" class="inputemail" placeholder="Email" />
</fieldset>
<fieldset >
<input type="password" name="pass" class="inputpassword" placeholder="Password" />
</fieldset >
<fieldset >
<button type="submit" class="submit">Submit</button>
</fieldset>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js"></script>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script type="text/javascript">
var socket = io.connect('http://192.168.1.3:9373');
</script>
</body>
</html>
chat.html
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div class="name"> Welcome </div>
<br></br>
<div class="chat"></div>
<form>
<input type="text" class="msg"> </input>
<button type="submit" class="enter">Send</button>
<input type="file" class="file"></input>
</form>
<script src="/socket.io/socket.io.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js"></script>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function(){
var socket = io.connect('http://192.168.1.3:9373');
var online=[];
var checkFile=0;
$.get("/getName", function(string){
username=string;
$('.name').append(username);
});
$('.enter').bind("click",function(){
$.get("/getMsg", function(){
setTimeout (function(){
socket.emit('chat message',$('.msg').val() );
$('.msg').val('');
},0);
});
return false;
});
socket.on('chatmessage', function(name,msg){
var block= $("<div class='message'> </div>");
if(msg.length){
var messenger= $("<div class='messenger'> </div>");
messenger.append(name);
block.append(messenger);
var text;
text=$("<div class='text'></div>");
text.append(msg);
block.append(text);
block.append($("<div class='pad'></div>"));
$('.chat').append(block);
}
});
});
</script>
</body>
</html>
server.js
var express = require('express')
, app = express()
, http = require('http')
, server = http.createServer(app)
, Twit = require('twit')
, io = require('socket.io').listen(server)
, os = require('os')
, open = require('open')
, bodyParser = require('body-parser')
, connect = require('connect')
, cookieParser = require('cookie-parser')
, session = require('express-session')
, sessionStore = session.MemoryStore()
, async = require('async')
, mysql = require("mysql");
var id=[];
var a;
server.listen(9373,'192.168.1.3');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser("secret"));
app.use(session({
store: sessionStore,
secret: "54321",
saveUninitialized: true,
resave: true
}));
app.get('/loginme', function (req, res) {
res.sendfile(__dirname + '/loginmysql.html');
});
app.get('/option', function (req, res) {
res.sendfile(__dirname + '/option.html');
});
app.get('/getName', function (req, res) {
var r = {};
r.name = req.session.userid;
res.send(r.name);
});
app.get('/getMsg', function (req, res) {
a = req.session.id;
res.json(a);
});
app.get('/chat', function (req, res) {
res.sendfile(__dirname + '/chat.html');
});
app.post('/valid', function (req, res) {
var username=req.body.email;
var password=req.body.pass;
var connection = mysql.createConnection({
"hostname": "localhost",
"user": "root",
"password": "vk123",
"database": "login"
});
connection.connect();
connection.query('SELECT * FROM id WHERE email=? AND password=?', [username,password], function(err, rows){
if (err){
throw err;
}else{
var name=rows[0].name;
req.session.userid = name;
id.push({sid:req.session.id, username:req.session.userid});
res.redirect('http://192.168.1.3:9373/option');
io.sockets.on('connection', function (socket){
io.emit('name',name);
});
}
});
connection.end();
});
io.sockets.on('connection', function (socket){
socket.on('chat message', function(msg){
var user;
var i;
for(i=id.length-1; i>=0; i--){
if(id[i].sid == a){
user=id[i].username;
break;
}
}
io.emit('chatmessage',id[i].username,msg);
});
});
app.use(express.static(__dirname+'/public'));