Node js displaying images from server - javascript

I am trying to display an image on a basic web page on a localhost w/ port 5000
here is main.js
var http = require('http');
var domain = require('domain');
var root = require('./root');
var image = require('./image');
function replyError(res) {
try {
res.writeHead(500);
res.end('Server error.');
} catch (err) {
console.error('Error sending response with code 500.');
}
};
function replyNotFound(res) {
res.writeHead(404);
res.end('not found');
}
function handleRequest(req, res) {
console.log('Handling request for ' + req.url);
if (req.url === '/') {
root.handle(req, res);
} else if (req.url === '/image.png'){
image.handle(req, res);
} else {
replyNotFound(res);
}
}
var server = http.createServer();
server.on('request', function(req, res) {
var d = domain.create();
d.on('error', function(err) {
console.error(req.url, err.message);
replyError(res);
});
d.run(function() { handleRequest(req, res); });
});
function CallbackToInit(){
server.listen(5000);
};
root.init(CallbackToInit);
Using callbacks I want the server to start listening(5000) only after the init function of the following code runs
var http = require('http');
var body;
exports.handle = function(req, res) {
res.writeHead(200, {
'Content-Type': 'image/png'
});
res.end(body);
};
exports.init = function(cb) {
require('fs').readFile('image.png', function(err, data) {
if (err) throw err;
body = data;
cb();
});
}
It's an assignment I can't use express
I am trying to get image.png to be displayed, I think body = data doesn't work because it can't hold an image like a string? I don't want to put any HTML into my js file.

Don't roll your own app server. Use one of the great web app frameworks like express or connect.
var express = require('express');
var app = express();
app.use(express.logger());
app.use(express.static(__dirname + '/public'));
app.listen(process.env.PORT || 5000);
Trust me, this is better.

Take a look at the node.js example for a simple http server or a tutorial/example, such as this, for serving static files through a simple server.

Related

How can i successfully create a simple form using nodejs without external modules

So i've been working on this for a bit:
/*
API 1 Docs: https://docs.genius.com/#/getting-started-h1
API 2 Docs: https://pastebin.com/doc_api
*/
let https = require('https')
//const qs = require('querystring');
function handler(req, res){
if(req.method == "GET"){
res.setHeader('Content-Type', 'text/html');
res.writeHead(200);
res.end("<html><body><form action='/' method='post'><input type='text' name='hello'><input type='submit'></form></body></html>");
} else if(req.method == 'POST'){
res.setHeader('Content-Type', 'text/html');
res.writeHead(200);
res.end(`<html>Success Posting!</html>`)
/*
var body;
req.on('data', function(data) {
body += data;
if (body.length > 1e6) {
// FLOOD ATTACK OR FAULTY CLIENT, NUKE REQUEST
req.connection.destroy();
}
});
req.on('end', function() {
var POST = qs.parse(body);
let data = POST.submit
res.end(`<html>${data}</html>`)
});
*/
} else {
res.writeHead(200);
res.end();
};
};
https.createServer(handler).listen(3000, function(err) {
if (err) {
console.log('Error starting https server');
} else {
console.log('Server listening on port 3000');
};
});
(Please ignore commented code)
I had it working before and all of a sudden, it stopped working, it created a form and upon submitting it it would change the page to "Success Posting" but now all of a sudden its not and ive been making small changes not knowing my problem
It appears that I need to create an http server using the http module instead of making an https server with the https module
Before:
const https = require('https')
https.createServer(handler).listen(3000, function(err) {
if (err) {
console.log('Error starting https server');
} else {
console.log('Server listening on port 3000');
};
});
After:
const http = require('http')
http.createServer(handler).listen(3000, function(err) {
if (err) {
console.log('Error starting http server');
} else {
console.log('Server listening on port 3000');
};
});

How to implement membership functions using Express & MySQL and JWT

I currently implemented login and membership functions using Express & MySQL.
And I want to add JWT.
I wanted to create an API only through Postman, not on the Web, and I heard that I had to use Passport to search.
And I know there is also Express-generate, but I want to modify my current code.
I am a beginner in Node.js and want a guide.
app.js
var express = require('express');
var http = require('http');
var static = require('serve-static');
var path = require('path');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var expressSession = require('express-session');
var expressErrorHandler = require('express-error-handler');
var mysql = require('mysql');
var pool = mysql.createPool({
connectionLimit:10,
host:'localhost',
user:'root',
password:'password',
database:'test',
debug:false
});
var app = express();
app.set('port', 3000);
app.use('/public', static(path.join(__dirname, 'public')));
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());
app.use(cookieParser());
app.use(expressSession({
secret:'my key',
resave: true,
saveUninitialized:true
}));
var router = express.Router();
router.route('/process/login').post(function(req, res) {
console.log('/process/login');
var paramId = req.body.id;
var paramPassword = req.body.password;
console.log('request parameter:' + paramId + paramPassword);
authUser(paramId, paramPassword, function(err, rows) {
if (err) {
console.log('error');
res.writeHead(200, '{"Content-Type":"text/plain; charset=utf-8"}');
res.write('<h1>error</h1>');
red.end();
return;
}
if (rows) {
console.dir(rows);
res.writeHead(200, '{"Content-Type":"text/plain; charset=utf-8"}');
res.write('<h1>user login success</h1>');
res.write('<div><p>user:' + rows[0].id + ' </p></div>');
res.end();
} else {
res.writeHead(200, '{"Content-Type":"text/plain; charset=utf-8"}');
res.write('<h1>user not found</h1>');
res.end();
}
});
});
router.route('/process/adduser').post(function(req, res) {
console.log('/process/adduser');
var paramId = req.body.id;
var paramPassword = req.body.password;
console.log('request parameter' + paramId + paramPassword);
addUser(paramId, paramPassword, function(err, addedUser) {
if (err) {
console.log('error');
res.writeHead(200, '{"Content-Type":"text/plain; charset=utf-8"}');
res.write('<h1>error</h1>');
red.end();
return;
}
if (addedUser) {
console.dir(addedUser);
res.writeHead(200, '{"Content-Type":"text/plain; charset=utf-8"}');
res.write('<h1>user added</h1>');
res.end();
} else {
res.writeHead(200, '{"Content-Type":"text/plain; charset=utf-8"}');
res.write('<h1>user added fail</h1>');
res.end();
}
});
})
app.use('/', router);
var addUser = function(id, password, callback) {
console.log('addUser');
pool.getConnection(function(err, conn) {
if(err) {
if (conn) {
conn.release();
}
callback(err, null);
return;
}
console.log('db threadid' + conn.threadId);
var data = {id:id, password:password};
var exec = conn.query('insert into users set ?', data,
function(err , result) {
conn.release();
console.log('SQL syntax' + exec.sql);
if (err) {
console.log('SQL error;');
callback(err, null);
return;
}
callback(null, result);
});
});
};
var authUser = function(id, password, callback) {
console.log('authUser' + id + password);
pool.getConnection(function(err, conn) {
if (err) {
if (conn) {
conn.release();
}
callback(err, null);
return;
}
console.log('db threadid:'+ conn.threadId);
var tablename = 'users';
var columns = ['id'];
var exec = conn.query('select ?? from ?? where id = ? and password = ?', [columns, tablename, id, password],
function(err, rows) {
conn.release();
console.log('SQL syntax' + exec.sql);
if (err) {
callback(err, null);
return;
}
if (rows.length >0 ) {
console.log('user find');
callback(null, rows);
} else {
console.log('user not found');
callback(null, null);
}
});
});
};
var errorHandler = expressErrorHandler({
static: {
'404' : './public/404.html'
}
});
app.use(expressErrorHandler.httpError(404));
app.use(errorHandler);
var server = http.createServer(app).listen(app.get('port'), function() {
console.log('server start' + app.get('port'));
});
Hi #yori If you want to create an API, first I will recommend parsing your data as JSON objects and thus eliminating all HTML tags in your code.
In order to use JWT for authentication, you will have to install the jsonwebtoken package as part of your project dependencies: https://www.npmjs.com/package/jsonwebtoken
I will recommend following the in-depth instructions in this post as a guide: https://medium.freecodecamp.org/securing-node-js-restful-apis-with-json-web-tokens-9f811a92bb52
For scope though, here is some explanation:
Express can be used to build robust APIs which can be made available for consumption. POSTMAN is a GUI tool that developers use to query APIs. curl commands is the terminal alternative. JWT is a safe way of representating claims transfered between two parties. I see the need to break down these terms to you so that you will understand the need, relevance and difference between each tool.
Following the guide in the article you will have to refactor your code a little bit.

Middleware getting executed multiple times?

I am trying to make a url shortener app using express. I have 2 middle wares for routes /shorten/:url* and /:code respectively. Somehow when I make requests like /shorten/iamarshad.com (requests that are not formatted and will fail my validateUrl method), middleware handling that request gets executed sometimes twice and sometime thrice. Why is this happening ?
Code for route.js:
var express = require("express");
var router = express.Router();
var crypto = require("./crypto");
var styles = "<style>#import url('https://fonts.googleapis.com/css?family=Cormorant+Garamond');" +
"body{background: #fefefe; word-wrap: break-word;}" +
"p {font-size: 30px;color: #b33c66;font-family: 'Cormorant Garamond', monospace;text-align: center;" +
"margin-top: 40vh;font-weight: 500;word-spacing: 2px;}</style>";
function verifyUrl(req, res, next) {
console.log("/shorten middleware called");
req.params.url += req.params[0];
console.log(req.params.url);
if (validateUrl(req.params.url)) {
req.db.collection("counter")
.find({_id: "counter"})
.toArray(function (err, docs) {
if (err) console.error("Error occurred while getting COUNTER document:", err);
req.encodedId = crypto.encode(docs[0].count);
next();
});
}
else {
var elem = "<p>Please enter correct and formatted url!</p>";
res.send(styles + elem);
}
}
function incrementCounter(req, res, next) {
// increasing counter
req.db.collection("counter")
.update(
{
_id: "counter"
},
{
$inc : {
count : 1
}
}
);
next();
}
function insertUrlDocument(req, res, next) {
//inserting new url document
var obj = {original_url: req.params.url, _id: req.encodedId, entry_time: new Date().toUTCString()};
req.db.collection("urls")
.insert(obj, function(err, data) {
if(err) console.error("Error happened while adding new document:", err);
});
next();
}
function sendResponse(req, res) {
var elem = "<p>" + JSON.stringify({'original_url': req.params.url, 'short_url': 'https://shorten-that.herokuapp.com/' + req.encodedId}) + "</p>";
res.send(styles + elem);
}
function validateUrl(url) {
var format = /(http:\/\/|https:\/\/)[a-z0-9\-]+[.]\w+/;
return (format.test(url));
}
router.get("/:code", function(req, res) {
console.log("/:code middleware called with url", req.params.code);
var code = req.params.code.toString();
// searching short-url-id
req.db.collection("urls")
.find({_id: code})
.toArray(function(err, docs) {
if(err) console.error("Error occurred while searching urls:", err);
console.log(docs);
if(docs.length > 0)
res.redirect(docs[0]["original_url"]);
else {
var elem = "<p>Oops, wrong url requested!</p>";
res.send(styles + elem);
}
});
});
// better solution needed
router.get("/shorten/:url*", [verifyUrl, incrementCounter, insertUrlDocument, sendResponse]);
module.exports = router;
Code for server.js:
var express = require("express")
, mongo = require("mongodb").MongoClient
, port = process.env.PORT || 8080
, path = require("path")
, routes = require("./routes")
, favicon = require("serve-favicon");
var app = express();
app.use(favicon(path.join(__dirname, 'public','favicon.png')));
app.use(express.static(path.join(__dirname, "public")));
var url = 'mongodb://localhost:27017/url-shortener';
mongo.connect(url, function(err, db) {
if (err) console.error("Error occurred while connecting to db:", err);
console.log("successfully connected to db.");
app.use(function(req, res, next) {
req.db = db;
next();
});
app.use("/", routes);
});
app.listen(port, function() {
console.log("App running on", port);
});

Reading data from NodeJs Serialport

I would like to be able to read data received by the ascii command sent.
Below is the code that sends command to my lock controller
var express = require('express');
var router = express.Router();
var SerialPort = require('serialport');
/* GET home page */
router.get('/', function(request, response){
SerialPort.list(function (err, ports) {
ports.forEach(function(port) {
console.log(port.comName);
console.log(port.pnpId);
console.log(port.manufacturer);
});
});
var port = new SerialPort("COM5", {
baudRate: 38400
});
port.on('open', function() {
// NodeJS v4 and earlier
port.write(new Buffer('status1', 'ascii'), function(err) {
if (err) {
return console.log('Error on write: ', err.message);
}
console.log('message written');
});
});
// open errors will be emitted as an error event
port.on('error', function(err) {
console.log('Error: ', err.message);
});
});
// Important
module.exports = router;
In the doc, it mentions the use of parsers to try and read data, https://github.com/EmergingTechnologyAdvisors/node-serialport#serialportparsers--object but I am not sure how to implement it, and I would want to execute after the command status1 has been written.
Essentially logs the response of the command succesfully written to the console
There are some peculiarities.
You can open port on application start and reconnect on port close or open port on each request. It defines how work with data flow. If you send request to port then answer can contain data of previous requests (more than one). You can ignore this problem (if answer is short and request interval is enough large) or send request with assign id and search answer with this id.
SerialPort.list(function (err, ports) {
ports.forEach(function(port) {
console.log(port.comName, port.pnpId, port.manufacturer); // or console.log(port)
});
});
router.get('/', function(req, res){
function sendData(code, msg) {
res.statusCode = 500;
res.write(msg);
console.log(msg);
}
var port = new SerialPort("COM5", {
baudRate: 38400
});
port.on('open', function() {
port.write(Buffer.from('status1', 'ascii'), function(err) {
if (err)
return sendData(500, err.message);
console.log('message written');
});
});
var buffer = '';
port.on('data', function(chunk) {
buffer += chunk;
var answers = buffer.split(/\r?\n/); \\ Split data by new line character or smth-else
buffer = answers.pop(); \\ Store unfinished data
if (answer.length > 0)
sendData(200, answer[0]);
});
port.on('error', function(err) {
sendData(500, err.message);
});
});
module.exports = router;

can't create a new directory using mongoose and express

Like the title entails.
I'm trying to make an application that when i put in certain info, it creates a link using mongoose _id. and express's app.get what i don't get is that to be able to join that directory i have to reload the whole server, which for the users and my sake a i don't want to do.
var mongoose = require("mongoose");
var express = require("express");
var app = express();
var http = require("http").Server(app);
var io = require("socket.io")(http);
var router = express.Router();
app.get("/", function (req, res) {
var ip = req.connection.remoteAddress;
res.sendFile(__dirname + "/index.html");
});
mongoose.connect("mongodb://localhost:27017/NEW_DB1");
console.log("Connection to database has been established");
var collectedData = new mongoose.Schema({
ipAddress: String,
name: {
type: String,
unique: false
}
});
var collectionOfData = mongoose.model("dataType", collectedData);
io.on("connection", function (socket) {
socket.on("name", function (e) {
var ip = socket.request.socket.remoteAddress;
var dataBase = mongoose.connection;
var Maindata = new collectionOfData({
ipAddress: ip,
name: e
});
Maindata.save(function (err, Maindata) {
if (err) {
return console.error(err);
} else {
console.dir(Maindata);
}
});
});
});
app.get("/mix", function (req, res) {
collectionOfData.find(function (err, data) {
res.send(data);
});
});
collectionOfData.find(function (err, data) {
data.forEach(function (uniqueURL) {
app.get("/" + uniqueURL._id, function (req, res) {
res.send("<h1>Hello " + uniqueURL.ipAddress + "</h1><p>" + uniqueURL.name + "</p>");
});
});
});
http.listen(10203, function () {
console.log("Server is up");
});
So what i'm trying to do is make it so i don't have to reload the whole server, and i'm able to just join the created directory when it's done being loaded.
figured i should put a quick example:
localhost:10203/55c2b2f39e09aeed245f2996
is a link a user just created the long
55c2b2f39e09aeed245f2996
is the effect of the _id, but when the user try's to connect to that site it won't work until i reload the server and obviously i'd like to avoid that haha.
I have a index.html file, but all that has is a socket.emit that sends "name" to the server
app.get("/", function (req, res) {
var ip = req.connection.remoteAddress;
res.sendFile(__dirname + "/index.html");
});
app.get('/:uniqueURL', function(req, res){
var id = req.params.uniqueURL;
res.send("Your requested id : " + id);
})
Try to use this above.
You are creating fix get path inside collectionData.find. That is the problem. So each time you have to reload the server by restarting.

Categories