How to send data using socket in nodejs - node.js

I want to send a data from html page to nodejs server.I want by pressing a button "desactivate my account" a prompt window apperas and when a user enter yes the username of connected user was sent to server to destroy the model from the database.
profile.ejs:
<div class="form-group">
<label class="col-md-3 control-label">Username:</label>
<div class="col-md-8">
<input class="form-control" id="username" name="username" value=<%= user.username %> type="text">
<div class="form-group">
<label class="col-md-3 control-label"></label>
<div class="emaillogin">
<a class="btn btn-default email-signin-button" role="button" onclick="desactive()"><i class="fa fa-trash-o fa-fw"></i> <span class="network-name" >Desactivate my account</span></a>
</div>
</div>
<script src="socket.io/socket.io.js"></script>
<script>
function desactive(){
var desactiv=prompt("Are you sure to desactive your account?");
var maj=desactiv.toUpperCase();
if(maj =="YES"){
var socket=io.connect();
var user1=$("#username").value;
socket.emit("desactiv",user1);
}
else{
alert("no");
}
}
</script>
The problem with the function mentioned below I can't send the username of the user I got null in the server side.However the user.username was displayed on the html page.what's my mistake?

jQuery object doesn't have value property - it's $("#username").val(); method
var socket=io.connect();
var user1=$("#username").val();
// not
var user1=$("#username").value;

Related

How can I send notifications to users who are offline in vuejs using `Notification` object?

I want make a Notification sender for my website I use Notification Object and socket.io.I create a Page to write title and body of notification .
notification is working and send notification to user that online in website.
but I want sent to offline user too.
I make this site useing vuejs and nodejs in back-end.
This is my socket that send notification in to server :
export default{
data(){
return{
title:"",
text:"",
socket: io("http://localhost:2000"),
}
};
methods:{
sendNotification(){
this.socket.emit("sendingNotification",{title:this.title,text:this.text});
}
};
}
I get title and text of this form :
```
<div class="content-wrapper" style="min-height: 915.8px;">
<section class="content">
<div class="row">
<div class="col-md-6">
<div class="box box-info">
<div class="box-header with-border">
<h3 class="box-title">ارسال نوتیفیکیشن </h3>
</div>
<!-- /.box-header -->
<!-- form start -->
<form class="form-horizontal">
<div class="box-body">
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">سرتیتر</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="inputEmail3" placeholder="سرتیتر" v-model="title">
</div>
</div>
<div class="form-group">
<label for="inputPassword3" class="col-sm-2 control-label">متن</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="inputPassword3" placeholder="متن " v-model="text">
</div>
</div>
</div>
<!-- /.box-body -->
<div class="box-footer">
<button type="submit" #click.prevent="sendNotification" class="btn btn-info pull-right">ارسال</button>
</div>
<!-- /.box-footer -->
</form>
</div>
</div>
</div>
</section>
</div>
```
this is my socket.io code in Nodejs :
let express = require('express');
let app=express();
let http = require('http').createServer(app);
let io = require('socket.io')(http);
io.on('connection', socket => {
socket.on("sendingNotification",(bodyMessage)=>{
console.log(bodyMessage);
io.emit("sendNotification",bodyMessage);
});
});
http.listen(2000);
and I get above event in to vuejs file And send Notification:
socket.on("sendNotification", body => {
const not=new Notification(body.title,{
body:body.text,
});
});
anyone can help show notifications sent offline to users after they are online

File upload using ftp and electron

I'm new to StackOverflow. I have started an electron project and I want to implement inside it the ability for the user to upload files using FTP. I've googled a bit and I've found a nice node module jsftp that is fit all my needs. The problem is that I'm new to electron and node coding, and I don't know how to manage the file upload. I've tried to use a standard file input but without success. My question is, how I can implement the file selection from the user and then upload the selected file to the FTP server?
Here is my code snippet:
HTML
<!-- Upload form row -->
<div class="row justify-content-center" id="">
<div class="col-8">
<form method="POST" action="/process-form" enctype="multipart/form-data" id="file-uploader">
<div class="form-row">
<div class="col-6">
<label for="file_name">File name</label>
<input type="text" class="form-control" id="file-name" name="file_name" placeholder="Nome file" />
</div>
<div class="col-6">
<label>Select file</label>
<div class="custom-file">
<input type="file" class="custom-file-input" name="uploaded_file" id="customFile" />
<label class="custom-file-label" for="customFile">Seleziona file</label>
</div>
</div>
<div class="col-12">
<label for="file_description">Description</label>
<textarea class="form-control" name="file_description" placeholder="Descrizione"></textarea>
</div>
<div class="col-12">
<button type="submit" name="upload_file" class="btn btn-link" id="process-form">UPLOAD</button>
</div>
</div>
</form>
</div>
</div>
JS code:
<!-- init app and xhr requests-->
<script type="text/javascript">
const jsftp = require('jsftp');
const bsCustomFileInput = require('bs-custom-file-input');
let ftp;
$(document).ready(function(){
$('#login-modal').modal('show');
$('#login-form').submit(function(e){
e.preventDefault();
var host = $('#host-field').val();
var user = $('#user-field').val();
var pass = $('#password-field').val();
ftp = new jsftp({
host: host,
port: 21, // defaults to 21
user: user, // defaults to "anonymous"
pass: pass, // defaults to "#anonymous"
});
ftp.list('public_html', (err, res) => {
console.log(res);
});
console.log(ftp);
});
bsCustomFileInput.init();
$('#file-uploader').submit(function(e){
console.log(ftp);
e.preventDefault();
var formData = new FormData($('#file-uploader')[0]);
var filename = $('#file-name').val();
ftp.put(formData, "mysubdomain.testing.net/"+filename+".jpeg", err => {
if(!err){
console.log("File transferred successfully!");
}
else{
console.log(err);
}
});
});
});
</script>

How to use endpoint inside another endpoint in express node js

I am just stuck in a problem and also don't know whether the question is correct or not.
I am working on a node express js, using ejs templating engine.
I have created certain endpoints (say login(POST) endpoint) which are generic endpoints.
Now I want to create a new application which uses should use these endpoints and render the view according to the result of these endpoints.
Lets say I have a generic endpoint for login
router.post('/user/login', function (req, res) {
var userLoginId = req.body.username;
var currentPassword = req.body.password;
UserLogin.findOne({userLoginId: userLoginId, currentPassword: currentPassword}, function (err, usr) {
if (err) {
console.log('Error in User login');
console.log(err);
res.status(500).type('application/problem+json').send();
} else {
if (!usr) {
console.log('Please enter valid username and password');
res.status(404).type('application/problem+json').send();
} else {
res.type('application/json').status(200).send(usr);
}
}
});
});
And I am using this login.ejs file
<div class="container panel panel-primary">
<h2 class="h2 text-center">Login</h2>
<form class="form-horizontal" name="loginForm" method="post" action="/user/login">
<div class="form-group">
<label for="username" class="col-sm-offset-2 col-sm-2 control-label">UserName</label>
<div class="col-sm-4">
<input type="text" name="username" class="form-control" id="username" placeholder="username">
</div>
</div>
<div class="form-group">
<label for="password" class="col-sm-offset-2 col-sm-2 control-label">Password</label>
<div class="col-sm-4">
<input type="password" name="password" class="form-control" id="password" placeholder="Password">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-4 col-sm-4">
<button type="submit" class="btn btn-primary btn-">Sign in</button>
</div>
</div>
</form>
</div>
Now I want to use this code and want to login to the system.
If the user login is successful I want to redirect to dashboard page else same login page.
On executing this code the api returns me the JSON response and from this response how can I decide to whether to redirect on dashboard page or login page.
Please help if more input is needed please put a comment.
I would instead of doing a form request to login, do a AJAX request to login and then use something like jQuery to do the AJAX request and response. Alternatively you could do something like the following.
router.get('/login', function(req, res){
res.render('login', {});
})
router.post('/login', function (req, res) {
var userLoginId = req.body.username;
var currentPassword = req.body.password;
UserLogin.findOne({userLoginId: userLoginId, currentPassword: currentPassword}, function (err, usr) {
if (err) {
console.log('Error in User login');
console.log(err);
// res.status(500).type('application/problem+json').send();
res.status(500).render('login', { error : 'Error finding password'})
} else {
if (!usr) {
console.log('Please enter valid username and password');
// res.status(404).type('application/problem+json').send();
res.status(404).render('login', { error : 'Please enter valid username and password'})
} else {
res.redirect('/dashboard');
}
}
});
});
For the login.ejs file i would conditionally render the error.
<!DOCTYPE html>
<html>
<body>
<div class="container panel panel-primary">
<h2 class="h2 text-center">Login</h2>
<%if (locals.error) { %>
<%= error %>
<% } %>
<form class="form-horizontal" name="loginForm" method="post" action="/user/login">
<div class="form-group">
<label for="username" class="col-sm-offset-2 col-sm-2 control-label">UserName</label>
<div class="col-sm-4">
<input type="text" name="username" class="form-control" id="username" placeholder="username">
</div>
</div>
<div class="form-group">
<label for="password" class="col-sm-offset-2 col-sm-2 control-label">Password</label>
<div class="col-sm-4">
<input type="password" name="password" class="form-control" id="password" placeholder="Password">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-4 col-sm-4">
<button type="submit" class="btn btn-primary btn-">Sign in</button>
</div>
</div>
</form>
</div>
</body>
</html>

Pass Data from MongoDB to Bootstrap Modal Using EJS

I'm building an express app which comprises ejs and bootstrap for rendering views, node and express for server side and mongodb for storage.
I have a form (contained in a modal) in which I can post data. After submitting the form, the values are saved to mongodb.
Here's the snippet for edit:
<td><%= cats.image %></td>
<td><a type="button" data-toggle="modal" data-target="#editCategory" href="#">Edit</a>
// without using the modal above, I'll have to create a new page to edit only one item
// I think it's a waste of page space and bad UX, so I am going with the modal
<!--<a href="/admin/categories/edit-category/<%= cats._id %>">--> // I want to get the values from this id and show in the modal
<!--<button type="button" class="btn btn-primary btn-sm">Edit</button>-->
<!--</a>-->
</td>
When I click on the edit button, I want to get the id of the item and retrieve it's values to display in the modal.
Here's the full modal view:
<!-- Edit Category Modal -->
<div class="modal fade" id="editCategory" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<form action="/admin/categories/edit-cateory/<%= %>" method="post" enctype="multipart/form-data">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span> </button>
<h4 class="modal-title" id="myEditCategoryLabel">Edit Category</h4>
</div>
<div class="modal-body">
<div class="form-group">
<label>Title</label>
// this value should come from the category id but don't know how to pass it
<input value="<%= %>" name="title" class="form-control" type="text" placeholder="Category Title"> <br>
<label>Upload Image</label>
<input class="form-control selImg" type="file" accept="image/*" onchange="showImage.call(this)">
<img src="#" class="imgPreview" style="display: none; height: 100px; width: 100px">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-primary">Save Edits</button>
</div>
</form>
</div>
</div>
</div>
How can I pass the data from mongodb to the modal using ejs?
Any help will be much appreciated.
Store your ID somewhere: hidden inputs or data-attributes.
<tr data-id="<%= cats.id %>">
<td><%= cats.image %></td>
<td>
<a type="button" class="edit" href="#">Edit</a>
</td>
</tr>
Then, create an onclick event handler such that, upon clicking on the button,
it will fetch the extra data via AJAX and open the modal dynamically after you get a response.
$('a.edit').click(function (e) {
e.preventDefault();
var tr = $(this).closest('tr'),
modal = $('#editCategory');
// make AJAX call passing the ID
$.getJSON('/admin/categories/get-cateory/' + tr.data('id'), function (data) {
// set values in modal
modal.find('form').attr('action', '/admin/categories/get-cateory/' + tr.data('id') );
modal.find('[name=title]').val( data.title );
// open modal
modal.modal('show');
});
});
You will need to create a route for fetching a single object (I'll leave that to you)
app.get('/admin/categories/get-cateory/:id', function (req, res) {
// TODO: fetch data using passed ID
// once you have the data, simply send the JSON back
res.json(data);
});

NodeJS Uncaught reference error for EJS variable that isn't required in page render

I am getting an uncaught reference error for a variable 'profile_image' that isn't used in the page render when attempting to check GET variable 'message' for 'error'. The 'profile_image' is used in the 'partials/header' however this particular render is using 'partials/header-shadow'. I am using a similar <% if //condition {} %> on another page with the same partials and it works okay, and if I remove the <% if //condition {} %> statement from this page it works okay too. I can't figure out why this particular page doesn't work, any ideas?
here is the EJS:
<% include partials/index-header-shadow %>
<div class="container">
<div class="col col-1-1">
<div class="wrapper no-scroll">
<div class="signup-form">
<div class="signup-form-inner">
<h3>Sign Up</h3>
<% if ( message == "error") { %>
<span class="error">This email is already being used, you can login to your account by clicking the link below</span>
<% } %>
<form action="/sign_up" method="post">
<input type="text" name="name" placeholder="Username" required/>
<span class="error">Please enter a username</span>
<input type="email" name="email" placeholder="Email Address" required/>
<span class="error">Please enter a valid email address</span>
<input type="password" name="password" pattern=".{6,}" placeholder="Password (minimum 6 characters)" required/>
<span class="error">Please enter a password</span>
<input type="hidden" name="profile_image" value="images/profile_images/user_icon.png"/>
<input type="submit" name="submit" class="submit-btn" value="Sign Up" />
</form>
<div class="login-link">
Already have an account? Log in here
</div>
</div>
</div>
</div>
</div>
</div>
<% include partials/footer %>
And here is the Server Render:
/* GET Sign_Up page. */
app.get('/sign_up',
function(req, res){
res.render('sign_up',
{
title: 'Utasko | Sign Up',
});
});
/* GET Sign_Up POST data. */
app.post('/sign_up', passport.authenticate('signup', {
successRedirect: '/login?message=success',
failureRedirect: '/sign_up?message=error'
}));
You need to pass the message parameter. in your case
app.get('/sign_up',
function(req, res){
res.render('sign_up',
{
title: 'Utasko | Sign Up',
message:req.query.message
});
});

Resources