accessing variable of node into html file - javascript

I have an index.html file and an app.js nodejs file. I have a var in app.js which is the name and want to print that variable in my index.html page
Code
var name = "Utsav";
var HTTP = require('HTTP');
var fs = require('fs');
function onRequest(req, res){
fs.readFile('index.html', function(err, data) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
res.end();
});
}
<html lang="en">
<head>
<title>Enter your request</title>
</head>
<body>
<label for="Name:">Name</label><br>
<input type="text" id="req"><br>
</body>
I want the value of name from app.js to print in a text box in index.html

For displaying data in your index.html, you can pass it like this.
app.get('/profile', function(request, response) {
response.render('pages/profile', {
user : request.user
});
})
and then in the html, you can view it like this.
<div>
<form>
<fieldset>
<input type = "text" value = "<%= user.user.username %>" />
</fieldset>
</form>
</div>
Hope it helps :)

Related

How to fix TypeError when saving HTML Canvas image to database using NodeJS and Multer?

I am trying to save a HTML Canvas image to MongoDB using Multer.
To test if my backend ( node + mongoose ) is working correctly, I created a form to upload the images I already have and that is saving to the database successfully.
To save the canvas image, I am making a JQuery ajax POST request after converting the image to a File. I am doing this inside the external JavaScript of the static drawing app which also contains few event listeners. I get this error:
data: fs.readFileSync(path.join(__dirname + '/../uploads/' + req.file.filename)),
^
TypeError: Cannot read properties of undefined (reading 'filename')
the external JS:
async function submitDrawing(username){
if(mode==0) context.fillStyle = 'white';
else context.fillStyle = 'black';
context.globalCompositeOperation = 'source-over';
context.clearRect(0, 0, saveCanvas.width, saveCanvas.height);
context.fillRect(0, 0, saveCanvas.width, saveCanvas.height);
context.drawImage(canvass,0,0);
await saveCanvas.toBlob(blob => {
var image = new File([blob], "image");
var name = $("#name").value;
let fd = new FormData();
fd.append("name",name);
fd.append("username",username);
fd.append("image",image);
$.ajax({
method : "POST",
url : "http://localhost:5000/postDrawing",
body: fd,
enctype: 'multipart/form-data',
processData: false, // don't let jquery process the data
contentType: false,
cache: false
})
});
}
In the node app, this is routes.js :
//importing all necessary stuff...
var multer = require('multer');
var storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, 'uploads')
},
filename: (req, file, cb) => {
cb(null, file.fieldname + '-' + Date.now())
}
});
var upload = multer({ storage: storage });
router.post('/postDrawing',upload.single('image'),postDrawing);
postDrawing function :
const postDrawing = async (req, res, next) => {
//creating object according to the mongoose schema I have.
var obj = {
name: req.body.name,
username: req.body.username,
img: {
data: fs.readFileSync(path.join(__dirname + '/../uploads/' + req.file.filename)),
contentType: 'image/png'
}
}
let im = new imgModel();
im.name = obj.name;
im.username = obj.username;
im.img = obj.img;
const temp = await im.save();
//res.send(temp);
}
the form which uploads to database successfully, just for reference :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Image Uploading</title>
</head>
<body>
<h1>To Upload Image on mongoDB</h1>
<hr>
<div>
<form action="/postDrawing" method="POST" enctype="multipart/form-data">
<div>
<label for="name">Image Title</label>
<input type="text" id="name" placeholder="Name"
value="" name="name" required>
</div>
<div>
<label for="username">username</label>
<textarea id="username" name="username" value="" rows="2"
placeholder="username" required>
</textarea>
</div>
<div>
<label for="image">Upload Image</label>
<input type="file" id="image"
name="image" value="" required>
</div>
<div>
<button type="submit">Submit</button>
</div>
</form>
</div>
</body>
</html>
please help me out in uploading the canvas image to database.Thank you.

Apostrophe in textarea Javascript

I create a sort of a company forum. Users can create post to share an information. To do so and at the moment, they complete a form with a basic textarea. My problem is that when they write a word with an apostrophe, the code interpret the apostrophe as single quote and it create en exception. I show you the code and an exemple below.
Html :
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="utf-8">
</head>
<body>
<div id="admin">
<div v-if="seenNews" id="news">
<div class="form">
<h4>Create a post</h4>
<form class="newPost" action="/newPost" method="POST">
<label id="titleLabel" for="titleInput">Title : </label>
<input type="text" id="titleInput" name="titleInput" required>
<label id="contentLabel" for="contentInput">Content : </label>
<textarea id="contentInput" name="contentInput" cols="40" rows="5" required></textarea>
<button type="submit">Create</button>
</form>
</div>
</div>
</div>
</body>
</html>
Back-end javascript :
app.js
const Server = require('./server/Server');
const express = require('express');
const DAO = require('./server/DAO');
const server = new Server();
server.start();
const dao = new DAO();
dao.connect();
server.app.post("/newPost", function(req, res) {
try {
dao.newPost(req.body.titleInput, req.body.contentInput).then(value => {
res.redirect('/Admin');
})
} catch (e) {
console.log(e);
}
})
DAO.js
const sql = require('mssql');
class DAO {
constructor() {
this.sqlConfig = {
user: 'username',
password: 'password',
server: 'SERVER',
port:port,
database: 'DB',
options: {
enableArithAbort: false,
encrypt:false
}
}
}
async newPost(title, content) {
try {
let req = 'INSERT INTO DB.dbo.[Table] (title, content) VALUES (\''+title+'\',\''+content+'\')';
console.log(req);
await sql.query(req).then(value => {
return true;
});
} catch (e) {
console.log(e);
return false;
}
}
}
As exemple, if a user create a post with this content : Ms. Smith's keys are at the reception desk, I would have this in console :
RequestError: Unclosed quotation mark after the character string ')'.
Maybe if I create a function to find en encode the character it can fix it, but I don't see how I can do so.
I finally use the JS function replace() to replace simple quote in my string by two simple quote. '' is the equivalent of js \' in sql server.
'INSERT INTO PROFACE.dbo.[Posts] (title, content) VALUES (\''+title.replace(/'/gi,"''")+'\',\''+content.replace(/'/gi,"''")+'\')'

socket.on doesn't work outside io.sockets.on('connection,..)

I have tried to catch a message from a routing page in this way:
ROUTING PAGE
router.get('/', function(req, res, next){
var socket= req.app.get('socketio');
socket.on('Ok', () => console.log("OK"));
res.render('exercises', {title: 'Exercises', ex: values[0]});
})
APP.JS
io.sockets.on('connection', function(socket){
console.log('Connesso');
app.set('socketio', socket);
})
In order to catch an 'Ok' event from the client in the routing page, but it's doesn't work and I don't figure out why because I've passed socket with app.set
EDIT
I emit the event here:
<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
<link rel='stylesheet' href='/stylesheets/style.css' />
</head>
<body>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost:8080/');
</script>
<div id="addex" hidden>
<form name="newex" method="get">
<h1>Inserisci esercizio</h1>
<p>Nome</p>
<input id="name" name="name" type="text"></input>
<p>Descrizione</p>
<input id="description" name="description" type="text"></input>
<input type="submit"></input>
</form>
</div>
<button id="add" type="button" onclick=""> Add </button>
<h1><%= title %></h1>
<p>Welcome to <%= title %></p>
<ul>
<p>Excercises:</p>
<% ex.forEach(value => { %>
<li><%= value.name %></li>
<% }); %>
</ul>
<script type="text/javascript">
add.onclick = function(event){
addex.hidden = false;
}
newex.onsubmit = function(event){
event.preventDefault();
socket.emit('message', {name: document.getElementById('name').value, desc: document.getElementById('description').value});
}
</script>
</body>
</html>
Try to follow this example:
const socketServer = SocketService.io = socketIo(server, {
path: process.env.WEBSOCKETS_PATH || "/socket.io",
handlePreflightRequest: (req, res) => {
const headers = {
"Access-Control-Allow-Headers": "Content-Type, Authorization",
"Access-Control-Allow-Origin": req.headers.origin ? req.headers.origin : "*", // or the specific origin you want to give access to,
"Access-Control-Allow-Credentials": true,
};
res.writeHead(200, headers);
res.end();
},
});
export let socketConnection;
socketServer.on("connect", async (connection) => {
logger.log("Successfully established socket connection.");
connection.emit("connection", { code: 200, message: "Socket connection established." });
socketConnection = connection;
connection.on("my event", async (streamConnection) => {
logger.log("Successfully established socket my event.");
connection.emit("connection", { code: 200, message: "My event established, listening on 'my event' event." });
});
});
Now in some other part of code you can import 'socketConnection', and use it.
.emit is to fire an event and .on listens for event.
With that being so, In your router code by doing socket.on('Ok', () => console.log("OK")); you are trying to listen to an event named Ok.
Now to listen to that event, there has to be an event fired named Ok. In your client by doing this socket.emit('message', ...) you are firing an event named message.
In your given code I don't see if you need this message or not but summary is to listen to and event named Ok you have to socket.emit('Ok', ...) somewhere else; your client in this case.
This is the bare basic of socket.io. I suggest you check the documentations and some tutorials because it was confusing for me in the beginning as well :)
Hope that helps you!
Cheers!

Mean stack controller server side not connecting to API

I am new to Mean stack and have been struggling with this for quite a few days.
To give you an idea of what I am trying to make; I am creating a tagging tool that stores all requests and their tags in a collection called tags and then also storing all of the distinct tags into the Tagnames collection. I would like to understand why my MEAN stack api layer gives me a 404 error.
This error only occurs with my put method in the server.js file.
TaggingTool\server.js
var express = require('express'),
app = express(),
bodyParser = require('body-parser'),
mongoose = require('mongoose'),
tagsController = require('./server/controllers/tagscontroller');
mongoose.connect('mongodb://localhost:27017/STDBank');
app.use(bodyParser());
app.get('/', function (req, res) {
res.sendfile(__dirname + '/client/views/index.html');
});
app.use('/js', express.static(__dirname + '/client/js'));
//REST API
app.get('/api/tags', tagsController.list);
app.get('/api/tagnames', tagsController.listName);
app.post('/api/tags', tagsController.create);
app.put('/api/tagUpdate/:id', tagsController.update);
app.listen(3000, function() {
console.log('I\'m Listening...');
})
TaggingTool\server\models\tag.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var TagSchema = new Schema({
request: String,
intentTag: String
}, {collection : "requests"});
module.exports = mongoose.model('Tag', TagSchema);
TaggingTool\server\models\name.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var nameSchema = new Schema({
name: String
}, {collection : "tags"});
module.exports = mongoose.model('TagName', nameSchema);
TaggingTool\server\controllers\tagscontroller.js
var Tag = require('../models/tag');
var TagName = require('../models/name');
module.exports.create = function (req, res) {
var tag = new Tag(req.body);
tag.save(function (err, result) {
res.json(result);
});
}
module.exports.listName = function(req, res){
TagName.find({}, function(err, results){
res.json(results);
});
}
module.exports.list = function (req, res) {
Tag.find({}, function (err, results) {
/*var arr = [];
for(var i = 0; i<results.length;i++){
if(results[i].intentTag){
console.log("enter if: ", results[i].intentTag);
}//end of if statement
else{
console.log("enter if: ", results[i].intentTag);
console.log("enters else statement ", arr);
arr.push({
_id : results[i]._id,
request : results[i].request
});
}//end of else statement
}//end of for loop
console.log("results ",arr);
*/
res.json(results);
});
}
module.exports.update = function(req, res){
console.log("Server side entered", res);
Tag.findByIdAndUpdate(req.params.id, {
$set: {
request: req.body.request,
intentTag: req.body.intentTag
}
}, function (err, tag){
if(err) res.send(err);
res.json(tag);
});
}
TaggingTool\client\js\controllers\tagsController.js
app.controller('tagsController', ['$scope', '$resource', function ($scope, $resource) {
var Tag = $resource('/api/tags');
var TagName = $resource('/api/tagnames');
var tagUpdate = $resource('/api/tagUpdate/:id');
Tag.query(function (results) {
$scope.tags = results;
});
TagName.query(function(results){
$scope.tagnames = results;
});
tagUpdate.query(function(results){
$scope.tags = results;
console.log("results: ", results);
});
//$scope.tags = [];
$scope.newtags=[];
console.log("tagReq", $scope);
$scope.newTag = function (index) {
console.log("newTag initiated");
var ntag = new tagUpdate();
console.log("_id: ", index);
var k = $scope.tagReq.request;
console.log("request: ", k);
var t = $scope.newTagName.tagname.name;
console.log("intentTag: ", t);
ntag._id = index;
ntag.request = $scope.tagReq.request;
ntag.intentTag = $scope.newTagName.tagname.name;
console.log("Tags: ", index);
$scope.ntag.$update({_id: index}, ntag);
}
$scope.createTag = function () {
var tag = new Tag();
tag.request = $scope.tagReq;
tag.intentTag = $scope.tagName;
tag.$save(function (result) {
$scope.tags.push(result);
$scope.tagName = '';
});
}
}]);
TaggingTool\client\js\app.js
var app = angular.module('taggingApp', ['ngResource'])
TaggingTool\client\views\index.html
<!DOCTYPE html>
<html ng-app="taggingApp">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Tagging Tool </title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<link rel="stylesheet" href="http://mbenford.github.io/ngTagsInput/css/ng-tags-input.min.css" />
<!-- Meetups View -->
<div ng-controller="tagsController">
<style type="text/css">
.tg {border-collapse:collapse;border-spacing:0;}
.tg td{font-family:Arial, sans-serif;font-size:14px;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;}
.tg th{font-family:Arial, sans-serif;font-size:14px;font-weight:normal;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;}
.tg .tg-yw4l{vertical-align:top}
</style>
<table class="tg">
<caption><b><strong><em>Requests and their Tags</em></strong></b></caption>
<tr ng-repeat="tag in tags ">
<th ng-model="tagReq">{{tag.request}}</th>
<th>
<select ng-model="newTagName" ng-options="tagname.name for tagname in tagnames">
<option value="" >Select Tag</option>
</select>
<form ng-submit="newTag(tag._id)">
<input type="text" placeholder="Tag Name" ng-model="newTagName.tagname.name"></input>
<input type="submit"/>
</form>
<p>{{newTagName.tagname.name}}</p>
<p>{{tagReq.tag.request}}</p>
</th>
</tr>
</table>
<form ng-submit="createTag()">
<input type="text" placeholder="Tag name" ng-model="tagName"></input>
<button type="submit">Add</button>
</form>
</div>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular-resource.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js"> </script>
<script src="http://mbenford.github.io/ngTagsInput/js/ng-tags-input.min.js"></script>
<script type="text/javascript" src="/js/app.js"></script>
<script type="text/javascript" src="/js/controllers/tagsController.js"> </script>
</body>
</html>
I apologize for the terrible code and coding conventions, if anyone could help I would be extremely thankful.
I assume, this problem only occurs when you try to update from your Angular client? If so: Angular's $resource does not have an update method using PUT methods by default, see here.
You will need to define this manually, something along the lines:
$resource('/api/tagUpdate/:id', { id: '#_id' }, {
'update': { method: 'PUT' }
});
You can then use the resource's update method for performing your update.
Additional hint: With regards to REST conventions, I would not call the URL tagUpdate, but rather tags or something like this. The fact that you're updating is given by the HTTP method PUT already.

Node js how to handle file response

Hi i am trying to do ajax image upload.this is the work i got so far.
my index.html:
//index.html
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title>File Upload showing Upload Progress</title>
<style>
* {
font-family: Verdana;
font-size: 12px;
}
</style>
</head>
<body>
<form action="/upload" method="post" enctype="multipart/form-data" id="MyUploadForm">
<input name="ImageFile" id="imageInput" type="file" />
<input type="submit" id="submit-btn" value="Upload" />
<img src="images/ajax-loader.gif" id="loading-img" style="display:none;" alt="Please Wait"/>
</form>
<div id="output"></div>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.7.1.min.js'></script>
<script type='text/javascript' src='main.js'></script>
</body>
<script type="text/javascript" src="js/jquery.form.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var options = {
target: '#output', // target element(s) to be updated with server response
beforeSubmit: beforeSubmit, // pre-submit callback
resetForm: true // reset the form after successful submit
};
$('#MyUploadForm').submit(function() {
$(this).ajaxSubmit(options); //Ajax Submit form
// return false to prevent standard browser submit and page navigation
return false;
});
});
//function to check file size before uploading.
function beforeSubmit(){
alert('ok');
//check whether browser fully supports all File API
if (window.File && window.FileReader && window.FileList && window.Blob)
{
if( !$('#imageInput').val()) //check empty input filed
{
$("#output").html("Are you kidding me?");
return false
}
var fsize = $('#imageInput')[0].files[0].size; //get file size
var ftype = $('#imageInput')[0].files[0].type; // get file type
//allow only valid image file types
switch(ftype)
{
case 'image/png': case 'image/gif': case 'image/jpeg': case 'image/pjpeg':
break;
default:
$("#output").html("<b>"+ftype+"</b> Unsupported file type!");
return false
}
//Allowed file size is less than 1 MB (1048576)
if(fsize>1048576)
{
$("#output").html("<b>"+fsize +"</b> Too big Image file! <br />Please reduce the size of your photo using an image editor.");
return false
}
$('#submit-btn').hide(); //hide submit button
$('#loading-img').show(); //hide submit button
$("#output").html("");
}
else
{
//Output error to older unsupported browsers that doesn't support HTML5 File API
$("#output").html("Please upgrade your browser, because your current browser lacks some new features we need!");
return false;
}
}
</script>
</html>
and my app.js
var express = require('express'); //Express Web Server
var bodyParser = require('body-parser'); //connects bodyParsing middleware
var formidable = require('formidable');
var path = require('path'); //used for file path
var fs =require('fs-extra'); //File System-needed for renaming file etc
var app = express();
app.use(express.static(path.join(__dirname, 'public')));
app.set('views', __dirname + '/views');
app.engine('html', require('ejs').renderFile);
/* ==========================================================
bodyParser() required to allow Express to see the uploaded files
============================================================ */
app.use(bodyParser({defer: true}));
app.route('/').get(function(req,res)
{
console.log("Server started!");
res.render('index.html');
res.end('done');
});
app.post('/upload', function(req, res) {
var form = new formidable.IncomingForm();
form.parse(req, function(err, fields, files) {
console.log(files);
res.send('fileinfo: ' +files);
});
});
var server = app.listen(3030, function() {
console.log('Listening on port %d', server.address().port);
});
I am getting the follwing response on server-side:
{ ImageFile:
{ domain: null,
_events: {},
_maxListeners: undefined,
size: 238027,
path: '/tmp/a7b06a71ff10de78cc8b941b18762b73',
name: 'bg.jpg',
type: 'image/jpeg',
hash: null,
lastModifiedDate: Sun Jun 01 2014 04:05:57 GMT+0530 (IST),
_writeStream:
{ _writableState: [Object],
writable: true,
domain: null,
_events: {},
_maxListeners: undefined,
path: '/tmp/a7b06a71ff10de78cc8b941b18762b73',
fd: null,
flags: 'w',
mode: 438,
start: undefined,
pos: undefined,
bytesWritten: 238027,
closed: true } } }
Now i want to know.How to move this file into upload folder. And also when i submit it goes in another page.I want to perform it without reloading is there any way for it in node? Thanks in advance.
fs-extra module has move method. Use it like this:
app.post('/upload', function(req, res) {
var form = new formidable.IncomingForm();
form.parse(req, function(err, fields, files) {
fs.move(files.ImageFile.path, __dirname + '/upload/' + files.ImageFile.name, function(err) {
if (err) return console.log(err);
console.log('Moved successfully');
});
res.send('fileinfo: ' + files);
});
});
So the uploaded file appears in upload folder with the original name. There are 2 caveats:
upload folder should exist;
if file with such name exists already it will not be overwritten, so maybe you should generate a unique filename on each upload (replace files.ImageFile.name with your unique filename).

Categories