How to show image, stored in MySQL on React page - mysql

I have images in MySQL. Trying to show one on my React page, so configured Express. Picture in DB stored as mediumblob and encoded in base64. There it looks like
iVBORw0KGgoAAAANSUhEUgAABQAAAAPACAYAAABq3NR5AAAgAElEQVR4AezBCZzXc+I4/uf70zSmTMd0rIqwSWzLLiK5i9....
so I configure Express to get this data:
const mysql = require("mysql");
const bodyParser = require("body-parser");
const express = require("express");
const app = express( );
const port = 4000;
app.use(bodyParser.json( ));
var mysqlConnection = mysql.createConnection({
host: "host",
user: "user",
password: "password",
database: "db"
});
mysqlConnection.connect((err) => {
if (!err) {
console.log("DB Connected");
} else {
console.log("DB Connection Failed " + err.message);
}
});
app.get("/rf", (req, res, next) => {
mysqlConnection.query(
"SELECT photo FROM photo WHERE id=365",
function(err, results, fields) {
if (err) throw err;
res.set("Access-Control-Allow-Origin", "*");
res.send(results);
}
);
});
app.listen(port, ( ) => {
console.log(`Listening at http://localhost:${port}`);
});
When trying to get data at http://localhost:4000/rf i receive not a base64 string, but Unit8Array, it looks like:
[{"photo":{"type":"Buffer","data":[105,86,66,79,82,119,48,75,71,103,111,65,65,65,65,78,83,85,104,69....
And I can't show it on the page. Help me please, or give me the sample of solving this problem.

Presumably you want to put an image tag in your web page looking something like this.
<img src="http://localhost:4000/rf" />
and get your /rf endpoint to deliver the image. If that's not the case please edit your question.
To do that, you must deliver the binary image to the browser with the correct MIME type. First decode it from Base64, then set the MIME type, then send it. It's possible code like this will help.
function(err, results, fields) {
if (err) throw err;
if (results && results.length >= 1) { /* results is an array */
const imgdata = Buffer.from(results[0].photo, 'base64')
res.type('png').send(imgdata)
}
Notice that most browsers will accept JPEGs. GIFs, and PNGs as long as they have any one of the valid MIME types (image/png for example). That is lucky for you, because it doesn't look like you store each image's MIME type in your table.
And, by the way, do your CORS stuff using the npm cors package, not by inserting extra CORS headers in your own code. CORS is a pain in the xxx neck to debug, and the package is already debugged.
Finally, be aware that storing images in databases scales up poorly. You don't want your MySQL server to be the bottleneck if you get tons of traffic. It's best to put your images in a static file system and store their paths in your database.

Related

HTML is being sent instead of JSON Data

I'm trying to retrieve data from a SQL database and display that said data on a Reactjs web app. However, all the calls I make to the database results in the HTML of the webpage in focus. I have set the headers, and I've tried to change the way the response from the express call is being handled.
Here is the expressjs script I am using right now:
const express = require('express');
const sql = require('mssql/msnodesqlv8');
const bodyParser = require('body-parser');
const path = require('path');
const cors = require('cors');
const db = require('./db.js');
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use('/counselling/triageadmin/', express.static(path.join(__dirname, '/build')));
app.use(cors());
app.get('/getTable', function (req, res, next){
var request = new sql.Request(db);
request.query('select * from Counselling order by TicketID desc', (err, result) =>{
if (err) { return next(err); }
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify(result["recordset"]));
});
});
From there, my axios calls look like this:
componentWillMount(){
let self = this;
axios.get("/getTable")
.then(function (response){
console.log(response.data);
self.setState({
data: response.data,
});
})
.catch(function (error){
console.log(error);
})
}
I added the console.log to check what was being returned, and as said, it was the HTML code of the current page of focus.
I made some changes to reflect what steps I took to get the 500 issue out. The current code, however, results in a 404.
If you move your get on top of your put it should work. The problem seems to be that the static clause resolves your request before it gets to your endpoint, so if you do this:
app.get('/counselling/triageadmin/getTable', function (req, res, next){
var request = new sql.Request(db);
request.query('select * from Counselling order by TicketID desc', (err, result) =>{
if (err) { return next(err); }
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify(result["recordset"]));
});
});
app.use('/counselling/triageadmin/', express.static(path.join(__dirname, '/build')));
the path to the get will attempt to be matched before you're routed to your static files.
Ideally you would want to have your rest endpoints under a different namespace, i.e. /api but if you decide to keep your setup, this should help.
I think your routes might be conflicting with each other. From the express documentation at: http://expressjs.com/en/4x/api.html#app.use
// this middleware will not allow the request to go beyond it
app.use(function(req, res, next) {
res.send('Hello World');
});
// requests will never reach this route
app.get('/', function (req, res) {
res.send('Welcome');
});
Thus, your route '/counselling/triageadmin/getTable' will never be reached, because your route '/counselling/triageadmin/' is intercepting it, responding with static resources.
To solve this, try organizing your routes in a way that puts all of your API requests at a different subfolder, like '/api'. So your getTable endpoint would be located at: '/api/counselling/triageadmin/getTable/' or something like that.
I'm also learning the MEAN stack and I stumbled upon your question since I had the opposite problem. I wanted it to respond with an HTML instead of a JSON
this line of code MAKES it respond with an HTML
res.send(JSON.stringify(result["recordset"]));
(I tried res.send("<h3 HTML T_T </h3>");) and it did send and HTML
however, if you try
res.json(String(req.params.id)); <= Notice the res.json instead of res.send
It responds with a JSON :)
I hope this helped

Node.js: Viewing string variable in my browser

So lets say I have a file called string.js, it might look something like this:
var hello = "Hello World!";
And lets say I have a file called hello.html.
How do I now view that string upon opening hello.html in my browser?
Your task can be divided into two parts:
1.add javascript codes to html and control then content
2.use node.js server to serve the html file up
The first task is pretty straightforward. You just have to include the .js file in your html. This is basic html-javascript application. You can find a lot of resource to learn it. W3schools is a very good site for beginners.
You have several ways to do task 2. Your objective is serve static contents. Let's use Hapi framework as an example.
'use strict';
const Hapi = require('hapi');
const server = new Hapi.Server();
server.connection({ port: 3000, host: 'localhost' });
server.register(require('inert'), (err) => {
if (err) {
throw err;
}
server.route({
method: 'GET',
path: '/sample',
handler: function (request, reply) {
reply.file('/your html file');
}
});
});
server.start((err) => {
if (err) {
throw err;
}
console.log(`Server running at: ${server.info.uri}`);
});
Now, once you enter localhost:3000/sample in your browser, you will be able to see the result.
In the code, what you did is creating a Hapi server and setting a route. The route replies you a html file once it is called.
Node.js runs server side. To be able to display Hello world, you would need to do something like:
const http = require('http');
http.createServer((req, res) => {
res.end('Hello World');
}).listen(3000);

How to display JSON file with Node.JS/Express

I'm VERY new to Node.js... so this is probably going to be stupid, basic. Here is what I am trying to do: I want to create a Node.js app that will query my MySQL database and return a JSON file to the user.
So far I have very little :) I have a project created with Webstorm. I have an index.js file and an index.ejs file. The index.js file has the following:
var express = require('express');
var router = express.Router();
var appdata = require('../data.json');
var mysql = require('mysql');
// http://nodejs.org/docs/v0.6.5/api/fs.html#fs.writeFile
var fs = require('fs');
var connection = mysql.createConnection({
host: 'xxxxxx',
user: 'xxxxx',
password: 'xxxxx'
database: 'xxxxx';
});
connection.connect();
router.get('/', function(request,response) {
connection.query('select AProgram_UID as UID, SiteDescription as Program, IcStatus as Status from AP_Details;', function (err, results, fields) {
if (err) {
console.log('Error in Query', err.message);
return response.send(500, err.message);
};
return JSON.stringify(results);
connection.end();
});
});
I haven't defined what goes in the index.ejs file because I really don't know where to go from here. I can write the JSON out to file from the code shown if I use writeFile, so I know the database part is correct.
Hopefully I explained enough... as mentioned, I'm new to Node. I just want to do something 'real' with it and this is something I need on a project I have.
Thanks!
In your router.get callback return the JSON back to the requester by using res.json to properly assign the Content-Type header to application/json and stringify whatever is passed to it.
Also you want to remove your return statements to before connection.end() otherwise connection.end() will never be called.
router.get('/', function(req, res) {
connection.query('select AProgram_UID as UID, SiteDescription as Program, IcStatus as Status from AP_Details;', function (err, results, fields) {
if (err) {
console.log('Error in Query', err.message);
res.status(500).send(err.message);
}
else
// render index view and pass in results JSON
res.json(results);
return connection.end()
});
});
Edit to use EJS View Engine Rendering
In order to use EJS you need to have your View Engine set to EJS and have a default Views directory setup. In your main Express server file it should look something like this before any routes
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
You'll need to change the code above from using res.json to use res.render. You'll also need to pass your results into the render function so the index.ejs can access the results JSON
res.render('index', { results: results });
In your index.ejs file you can access results using the EJS markup syntax
<html>
<body>
<p><% results %></p>
</body>
</html>

How to use express.js with mysql and express-myconnection?

I am using Express 4.9.0 and express-generator. Executed this command:
express --hbs projectname
Installed following modules with NPM:
mysql
express-myconnection
I want to make todo application. I have created separate file under routes/todo.js and created get/post routes for creating todos in that file using router.get and router.post.
i have following code in app.js:
// mysql connection
var connection = require('express-myconnection');
var mysql = require('mysql');
app.use(
connection(mysql, {
host : config.db.host,
user : config.db.user,
password : config.db.password,
database : config.db.database,
debug : false //set true if you wanna see debug logger
}, 'request')
);
// end of mysql connection
Where should i place mysql config and connection code? Inside todo.js? I still don't get concept of organisation file structure and where to place database queries.
I don't know if you eventually found the answer, but I thought it might help out others who accidentally stumbled on your question:
After you've setup like mentioned above, you can call the connection from the request object using the getConnection method like this:
exports.index = function(req, res) {
req.getConnection(function (err, connection) {
connection.query('select * from table_name', function(err, rows, fields){
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(rows);
}
});
});
};
This should print out a json with the content of your table all nice an pretty.
Hope this comes in handy.

Nodejs + Passport + MySQL

I'm trying to figure out how to use nodejs + Passport + MySQL. It seems as though just about every tutorial out there is using mongoDB and I don't want to do that. In fact some quick searches of this type will yield web pages like (http://nodejsrocks.blogspot.com/2012/04/nodejs-expressjs-mysql.html) and a youtube video that is a guy (https://www.youtube.com/watch?v=jGBbMVJx3h0) doing nothing but loging in, and who knows what he is really using, but the page has had 3K + views. I'd hope that some of the developers would look at that and say maybe there is a use for something like a comprehensive non MVC type of thing with MySQL. My reason for this is I am trying to get iOS and Android capabilities only and have no need for a large scaffolding overhead. Just the DB and server side scripting handling the queries and returning JSON objects to the phones.
So, that being said, can someone who has had real experience with this please help me out(And the rest of the world trying to do similar things without any in-depth tutorials, because we aren't using mongoDB and full blown scaffolding).
The tables I have set up for a 'TwitterStrategy' are users(id (PK), username, email, salt, password), and twitterusers(id (PK), name, screenname, location, description, url, img, token, tokensecret).
Here is the code I am trying to get going from a single main.js file. I know this is not best practices, and I plan to clean it up later, but for now, I would like to understand what I am missing and get things working. It would be extremely appreciated if someone can help, and I'm SURE others would find this very useful as well. Thanks.
var http = require('http'),
mysql = require('mysql'),
url = require('url'),
crypto = require('crypto'),
express = require('express'),
flash = require('connect-flash'),
passport = require('passport'),
TwitterStrategy = require('passport-twitter').Strategy;
var db = mysql.createConnection({
host : "****",
user : "****",
password : "****",
port : '****',
database : '****'
});
// Connect the connection to DB and throw error if exists
db.connect(function(err) {
if (err) {
console.error('Error connecting to db');
console.error(err);
return;
}
console.log('Database connected');
});
var TWITTER_CONSUMER_KEY = "****";
var TWITTER_CONSUMER_SECRET = "****";
passport.use(new TwitterStrategy({
consumerKey: TWITTER_CONSUMER_KEY,
consumerSecret: TWITTER_CONSUMER_SECRET,
callbackURL: 'http://127.0.0.1:3000/auth/twitter/callback'},
function(accessToken, refreshToken, profile, done) {
//db.query(SELECT ........ FROM ...... WHERE ........, function (err, user){
if (err) {
console.log(err);
}
if (!err && user != null){
done(null, result);
} else {
console.log(result);
}
})
});
}
));
passport.serializeUser(function(user, done) {
console.log('serializeUser: ' + user.id);
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
db.query('SELECT * FROM users WHERE id = ' + id, function(err, result) {
if (err){
console.log(err);
} else {
console.log(result);
}
if (!err) {
done(null, result);
} else {
done(err, null);
}
});
});
var app = express();
app.set(function(){
// app.set('views', __dirname + '/views'); // Definitely for some views which aren't being used here
// app.set('view engine', 'jade'); // Using jade for views, not used
// app.use(express.favicon()); // Not really sure this is important, should be web only
app.use(express.logger('dev')); // Again, not really sure this is important
app.use(express.bodyParser()); // Have no idea what this is used for
app.use(express.methodOverride()); // Same no Fn clue
app.use(express.cookieParser('what the F'));
app.use(express.session());
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
// app.use(app.router); // Here again we are defining our routes in main, so shouldn't need this.
// app.use(express.static(__dirname + '/public'));
});
var server = http.createServer(function(req, res) {
console.log('url: ' + req.url);
var params = url.parse(req.url, true)
var path = params.pathname;
if (path == '/signup') {
console.log("User signing up");
onSignUp(params, res);
} else if (path == '/signin') {
console.log("User signing in");
onSignIn(params, res);
} else if (path == '/auth/twitter'){
passport.authenticate('twitter'),
function(req, res){
console.log('Twitter User Created or Signed In');
}
}
});
//Keep server alive and listening to requests with DB connected also
server.listen(3000);
Am I missing another auth table? What is it that I need to put in the MySQL statement where the dots are so that I can find the user, and what parameters are being passed from the user request to get the query going, i.e. what is this oauth ID I have seen in tutorials that is getting passed from what seems to be the user to twitter for authorization? Also, what should I be expecting from this callback from Twitter? Anyway, I'll be glad to post all of this somewhere for everyone else to look at once I have a solution made so that all of us using MySQL and node don't get left out and have to search google to find something that seems as though it should be readily available, instead of copies of the same exact nodejs + mongoDB + express tutorial (with many that are out of date except for the scotch io, which looks very good if you wanna use mongo...might I add instances over at Amazon run about $279 estimated per month on the low end) that is floating around and being redistributed by nearly anyone with a "tutorial" out there. Thanks again.
Try wrapping strategy function under process.nextTick, e.g.,
passport.use(new TwitterStrategy({
consumerKey: TWITTER_CONSUMER_KEY,
consumerSecret: TWITTER_CONSUMER_SECRET,
callbackURL: 'http://127.0.0.1:3000/auth/twitter/callback'},
function(accessToken, refreshToken, profile, done) {
process.nextTick(function(){
// this is where you put logic to check the profile sent from twitter already in your DB or not,
// its totally up to you whether you keep a separate auth table for it or not
// NB: there will be some unique value in profile that can be used for next references
db.query(SELECT ........ FROM ...... WHERE ........, function (err, user){
if (err) {
console.log(err);
}
if (!err && user != null){
done(null, result);
} else {
console.log(result);
}
})
});
});
}
));
you also have to have a route for accepting the callback, e.g.,
app.get('/auth/twitter/callback', function(req, res, next) {
passport.authenticate('twitter',
{ },
function(err, user) {
// the result you send from the strategy function will be here
// do anything you like with the user send
}
)(req, res, next);
});
Hope it makes things clearer.