Displaying HTML in NodeJS - javascript

I need to display <img src="http://my.pic/test/rg/pict.png" /> from `items`.`img`
But when res.write(rows[0].img, 'utf8');,
I see in browser:
<img style="display: none !important;" src="http://my.pic/test/rg/pict.png" />
How do I fix style="display: none !important;"?
express = require('express'), app = express();
var mysql = require('mysql');
app.listen(8080);
mysql.connect = function(req, res, next){
var connect = mysql.createConnection({
host : 'localhost',
user : 'person',
password : 'ppasw',
database : 'db1'
});
return connect;
}
server.get(new RegExp('/img'), function(req, res, next){
var db =mysql.connect();
db.connect();
db.query("use `bd1`");
db.query("SELECT `img` FROM `items` WHERE `id`='" + intval(req.query.id) + "'",
function (err, rows, fields) {
res.setHeader("Content-Type", "text/html");
res.write(rows[0].img, 'utf8');
res.end();
});
db.end();
});
----*
I find problem - Adblock plugin.

Can you add this debug code before the res.write part ?
console.log(rows[0].img)
My best guess is that the style attribute is already in the database.
My second best guess is that you might have some javascript running in your browser which hides broken images.

Depending on the information on the database, you may have to construct the HTML. If you're only putting the URL to the image in there, it's not going to work right. You might have to do something like:
res.write('<html><body><img src="' + rows[0].img + '" /></body></html>');
If the database has all of the HTML already stored (I suggest not doing that) and you don't have any extensions hiding broken images, you're going to have to have some client side Javascript to unhide the image.

Related

Twilio call button and user input

so I've created this application that allows me to call a phone number from my Twilio account through localhost. I just have to put a / after the port # and the phone number I want to call(localhost:2222/7786453738) and it will send out a call. but I want the user to be able to make that call by inputting a phone number on to the webpage then clicking a button. is that possible? here's my code so far in the index.js file. I run it by going node index.js in the command terminal.
const express = require("express");
const app = express();
const port = 2222;
app.get("/", function(req, resp){
resp.end("welcome to my app");
});
app.get("/:data", function(req, resp){
var accountSid = 'accountSid'
var authToken = 'authtoken'
var client = require('twilio')(accountSid, authToken);
client.calls.create({
url: 'https://demo.twilio.com/welcome/voice/',
to: req.params.data,
from: '6043302056',
}, function(err, call) {
if(err) {
console.log(err);
} else {
console.log(call.sid);
}
})
console.log(req.params.data);
if(req.params.data == "me"){
resp.end("hi raj");
//resp.sendFile(__dirname+"/public/index.html)
} else {
resp.end("Now calling: "+req.params.data);
}
});
app.listen(port, function(err){
if(err){
console.log("error starting "+err);
return false;
}
console.log("port is running. "+port);
})
Twilio developer evangelist here.
You're most of the way there with what you want to achieve. You can absolutely create a form that will take an input from a user and dial the number they enter.
First up, You will want to update your route as the number you send through a form won't be a part of the path, instead it will come as part of the body of the request. In order to read request bodies in express, you will want the body-parser module. So, install that in your project with:
npm install body-parser --save
Then include it in your file and use it with your app:
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
Now, form's usually POST their data, rather than working over GET, so let's update your route to receive that POST request and extract the number from the request:
app.post("/calls", function(req, resp) {
const accountSid = 'accountSid'
const authToken = 'authtoken'
const client = require('twilio')(accountSid, authToken);
const number = req.body.number;
client.calls.create({
url: 'https://demo.twilio.com/welcome/voice/',
to: number,
from: '6043302056',
}, function(err, call) {
if(err) {
console.error(err);
} else {
console.log(call.sid);
}
})
console.log(number);
if(req.params.data == "me"){
resp.end("hi raj");
//resp.sendFile(__dirname+"/public/index.html)
} else {
resp.end("Now calling: " + number);
}
});
Now, you need an HTML file that will include a form to make the request to this endpoint. Create an HTML file called index.html and place it in a new folder in your application called public.
You can load static files from the public directory in express with this line, add it near the top, after you create the app:
const path = require('path');
app.use('/static', express.static(path.join(__dirname, 'public')));
Finally we just need the HTML. This is the simplest HTML I could write that would do what you need:
<!DOCTYPE html>
<html>
<head>
<title>Make a call</title>
</head>
<body>
<form action="/" method="POST">
<label for="number">What number do you want to call?</label>
<input id="number" type="tel" />
<button type="submit">Make call</button>
</form>
</body>
</html>
As you can see it is just a form with a single input, the number, and a button to submit it.
Give this all a go and let me know how you get on.
Yes,
first: you can do that, but you need to write the code in HTML File or at least include this code in html file, and call the Twilo's function after you click on the respective button. For that first, render a HTML page, after user enters the address, on that HTML Page give input number and call now button feature. and after user clicks on the button, do:
function callNow() {
var num = document.getElementById('number').value;
client.calls.create({
url: 'https://demo.twilio.com/welcome/voice/',
to: num,
from: '6043302056',
}, function(err, call) {
if(err) {
console.log(err);
} else {
console.log(call.sid);
}
{
Your HTML Code should be:
<input id="number">
<button onclick="callNow()">Call Now</button>
You can include twilio cdn and use this feature. I am just giving you the concept, I hope you will find this helpful.

Sending socket.io instance to express route

I am trying to create a nodejs app that will search in various web sites using their API. The result will be sent to the client as soon as it receive result from those API using socket.io. The front end will then add those result using jQuery.
What is the best way to implement this?
So Far I have tried:
Sample code 1
At first I created a middleware for express that add the socket to the request like -
var socketMiddleWare = function(req, res, next){
io.on('connection', function(socket){
console.log(io.engine.clientsCount + " clients connected.");
req.socket = socket;
socket.on('disconnect', function(){
console.log(io.engine.clientsCount + " clients after disconnec.");
});
});
next();
};
then added this middleware to my route -
app.use('/users', socketMiddleWare, users);
It works but the problem is it create multiple event listener each time user refresh the page.
Sample code 2
So then I tried (sample code)
io.on('connection', function(socket){
console.log("user connected");
global.socket = socket;
socket.on('disconnect', function(){
console.log("disconnect");
});
socket.on('my message', function(){
console.log("My message received");
});
});
and on my test route I did
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
if(socket){
socket.emit('response', 'nothing');
}
res.render('index', { title: 'Express' });
});
module.exports = router;
It solved the previous problem of multiple event listener on refresh But most of the time it can not emit the response. And even it emit my browser can not show the result. On client side I did something like this -
var socket = io.connect('http://localhost');
socket.on('response', function(data){
console.log(data);
document.getElementById("change").innerHTML += data;
});
I can see the response in browser console but my browser show the change for a few milliseconds before it disappear.
I think the the main problem is The page loads before establishing socket connection.
I am currently learning node.js and socket.io. So please help me.
Conclusion
I do have plan to add social network features like one to one message, live friends feed update on home page etc using socket.io in future. Please let me know if there is any good documentation or open source project that can help me implementing it.
I am searching for solution for last couple of days but with no luck so far. I am ready to learn any new methodology or fully rewrite my code.
TL;DR
When a user client search for item, push contents to the client that requested the content when new data available. Data is available after processing response from website like "The Movie Database" and "TheTVDB.com" through their API.
You can use the ID of the socket to keep track of which socket to send results to.
Client
When the user then searches for something the ID is included in the query parameters.
<body>
<form>
<!-- Disable the search bar until the socket is connected -->
<input type="search" name="q" placeholder="Search" disabled>
</form>
<div id="results"></div>
<script src="/socket.io/socket.io.js"></script>
<script>
var resultsElement = document.querySelector("#results");
var search = document.querySelector("form [type=search]");
var socket = io("http://localhost:3000");
socket.on("connect", function(){
search.disabled = false;
});
socket.on("results", function(results){
for(var i = 0;i < results.length;i++){
var result = document.createElement("div");
result.textContent = results[i];
resultsElement.appendChild(result);
}
});
document.querySelector("form").addEventListener("submit", function(event){
fetch("/search?socketID=" + encodeURIComponent(socket.id) + "&q=" + encodeURIComponent(search.value));
event.preventDefault();
});
</script>
</body>
Server
When the server receives the search request it gets the socket using the socket ID sent in the query parameters and starts sending results back to the client.
var app = require("http").createServer(handler);
var io = require("socket.io")(app);
var fs = require("fs");
var url = require("url");
app.listen(3000);
function handler(req, res) {
var query = url.parse(req.url, true).query;
if(req.url.startsWith("/search")){
var results = ["things", "stuff", "items"];
// Server-side IDs have "/#" in front of them
var socket = io.sockets.connected["/#" + query.socketID];
if(socket){
// Get and send "search results"
var interval = setInterval(function(){
var popped = results.pop();
if(popped){
socket.emit("results", [query.q + " " + popped]);
}else{
clearInterval(interval);
}
}, 1000);
}
res.writeHead(204);
res.end();
}else{
fs.readFile(__dirname + "/index.html", function(err, data) {
res.writeHead(200);
res.end(data);
});
}
}

How to implement push notification system on a mysql database with node.js

I'm totally new to node.js and I want to implement push notification system on a MySql database. I have a notification table in my database. In this table I have store recipient_id that specify the recipient of the notification. Now I want when a new notification with recipient_id is equal to current logged in user's id notify that user. Something like Stackoverflow If you are in the for example java tagged questions, every time a new question with java tag create, a notification appear on top of the page : 1 question with new activity.
Sorry for my poor English. Please help me to implement this system, because I'm new to it.
I have made a simple app like your requirement.
You can get help from following lines of code.You need to understand the basics of code. after that you will easily achieve your target. most of things from your requirement covered in this demo app.
Its not a exact but you will meet your target through this.
In this example a status post by any user will emit to all other users also at same time. we can manipulate it to achieve "1 new status".
make a table in database where your entries to be saved
CREATE TABLE status
(
`status_id` INT NOT NULL AUTO_INCREMENT,
`s_text` TEXT,
`t_status` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY ( `status_id` )
);
//server.js
var app = require("express")();
var mysql = require("mysql");
var http = require('http').Server(app);
var io = require("socket.io")(http);
/* Creating POOL MySQL connection.*/
var pool = mysql.createPool({
connectionLimit: 100,
host: 'localhost',
user: 'root',
password: '',
database: 'fbstatus',
debug: false
});
app.get("/", function(req, res) {
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket) {
console.log("A user is connected");
socket.on('status added', function(status) {
add_status(status, function(res) {
if (res) {
io.emit('new status', status);
} else {
io.emit('error');
}
});
});
});
var add_status = function(status, callback) {
pool.getConnection(function(err, connection) {
if (err) {
connection.release();
callback(false);
return;
}
connection.query("INSERT INTO `status` (`s_text`) VALUES ('" + status + "')", function(err, rows) {
connection.release();
if (!err) {
callback(true);
}
});
connection.on('error', function(err) {
callback(false);
return;
});
});
}
http.listen(3000, function() {
console.log("Listening on 3000");
});
//index.html
<html>
<head>
<title>Socket.io</title>
<script src="/socket.io/socket.io.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
<script src = "http://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
<script>
$(document).ready(function(){
var socket = io();
$("#add_status").click(function(){
socket.emit('status added',$("#comment").val());
});
socket.on('new status',function(msg){
var count = $('#count_status').text();
var valCount = parseInt(count);
if(valCount>=1) {
valCount = valCount+1;
} else {
valCount = 1;
}
var showMsg = '<div id="count_status"> '+valCount+' </div> new status';
$("#show_comments").html(showMsg);
});
});
</script>
</head>
<body>
<div id="comment_box" style = "padding:5%;">
<textarea id="comment" rows="5" cols="70"></textarea><br /><br />
<input type="button" id="add_status" value="Add">
</div>
<div id= "show_comments" class = "jumbotron"></div>
</body>
</html>
Run the app with following command
node Server.js
Now run http://localhost:3000/ in browser and to see the result open a new window in which you post a status and see your new status notification in both the window.
Thanks
Edited: This a great startup tutorial. a few thing needs modification.
connection.release() code ends up unreadable and not working. you should comets or remove it.
2.The actual output in my case:
You can do it 2 ways:
Query the server every n seconds for any new messages. Pass a timestamp of the last time you checked as a parameter and if any notification since the last check, return as json and display them in the client. This is called a pull strategy.
Or you can use websockets which maintains a permanent connection between your client and server, and then you can send notifications to the client from your server code in real-time. See socket.io tutorials. This is called a push strategy.

display a message before (or after) a redirect javascript

I'm trying to display a message after or before a redirect. I looked around the site but I found only jquery and php but I can only use the normal java language. In particular I'm trying to use a div that could be good for me. The problem is that the redirect is on the server side (so I cannot call a javascript function or I cannot put a document.getElementByID). Can you help me? Here is my code:
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 would put my message on the res.redirect('/login') (both of them) with two different message. I don't know if I have to create a new page, identical, with a div message or I could find a better solution...
I'm trying to display a message after or before a redirect...The problem is that the redirect is on the server side (so I cannot call a javascript function or I cannot put a document.getElementByID).
Exactly. So you can't do that. Instead, you need to return a redirect to a page with your message on it, and then have that page continue on (after a period of time, or after a user action) to the ultimate destination (/login or whatever).
A minimal intermediary page might look like this:
<!doctype html>
<html>
<head>
<title>Some Relevant Title</title>
<meta charset="utf-8"></meta><!-- Or whatever is appropriate -->
<meta http-equiv="refresh" content="15; url=/login">
</head>
<body>
Message goes here. With the refresh above, the page will refresh after 15 seconds.
</body>
</html>

browser display error after request node.js

i am trying to insert some data to database using node and mysql i manage to get it done, but after query response the browser loads continuously i tried pooling still nothing happens
Here is my code
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var bodyParser = require('body-parser');
var urlencodedParser = bodyParser.urlencoded({ extended: false })
var sql = require('mysql');
var pool = sql.createPool({
host : 'localhost',
user : 'root',
password : '',
port : '3306',
database : 'node'
});
app.get('/nodeThis', function (req, res) {
res.sendFile(__dirname + '/insert.html');
});
app.post('/nodeThis', urlencodedParser, function (req, res) {
var post={user_name:req.body.name1,user_what:req.body.what,user_why:req.body.why};
pool.getConnection(function(err, connection){
connection.query('INSERT INTO user SET ?', post, function(err){
if(err){
console.log(err);
}else{
console.log('succes');
}
});
connection.release();
});
});
server.listen(3000);
Here is how i pass the data from HTML to node
<html>
<body>
<div>
<form action="/nodeThis" method="post">
<input type="text" name="name1">
<input type="text" name="what">
<input type="text" name="why">
<button class="boom">Submit</button>
</form>
</div>
</body>
</html>
After the database operation, you aren't sending any response to the browser; you just sent an output to the console instead; the browser was waiting for a response that never came
If you insert res.sendFile(__dirname + '/insert.html'); or some other response after the console.log('succes');, you'll see an output on the browser.
That being said, I hope this is just a proof of concept and not a production code.
Update Based on the Comment
Retrieving the number of rows affected
After running the executing the database insertion function
db.query("insert into table", [data-to-insert], function(err, result){
//to retrieve the number of rows affected
var number_of_rows = result.affectedRows
})
the result has a property called affectedRows that allows the user to know how many rows were inserted, updated, or deleted.
To retrieve the primary id of the inserted row (if it has one), result has a property called insertId.
var id = result.insertId
Hope this helps!

Categories