Node.js: Viewing string variable in my browser - html

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);

Related

How to show image, stored in MySQL on React page

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.

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

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>

what's the best way to send a variable using method get with express, mysql and node.js

I'm building a web site using node.js express MySQL and boostrap, when I try to send a variable against method get for to do a query to the database, it's seem doesn't work, because there's no a good render. this is my code:
app.get('/reservaciones/leer/:id', function(req, res) {
var idreservacion = req.params.idreservacion;
crud.get_leer_reservacion(req,idreservacion,function(data_leer){
res.render'../views/leer.html',data:data_leer});
});
});
exports.get_leer_reservacion = function(req,idreservacion,fn){
// here the query
connection.query('select * from reservacion where idreservacion = '"+idreservacion+"'', function(err,rows){
if(err){
throw err;
}
return fn(rows);
});
};
https://drive.google.com/folderview?id=0BxFTEy90zOKAfmJOXzR3NDFLa081NUtEUFU4LWhuN2ZUTDMtVktPeHlYbVUzWW02a2pGWEk&usp=sharing
res.render'../views/leer.html',data:data_leer});
should be:
(outside of app.get:)
app.use('views', '../views');
(inside:)
res.render('leer',{data:data_leer});
If your problem is actually getting the templated data into the page I suggest the ejs npm package and templating system, you would use <%= data => to template in the value
In this code:
app.get('/reservaciones/leer/:id', function(req, res) {
var idreservacion = req.params.idreservacion;
You define a parameter called id, but you retrieve a parameter called idreservacion. Try something like this:
app.get('/reservaciones/leer/:id', function(req, res) {
var idreservacion = req.params.id;

Angular Seed project, set index.html by default

I am using the Angular Seed project to build a simple website. When i start the node server and enter the url at localhost:8000, it serves up the directory contents. I would like it to serve up the index.html file but would like to do this without a redirect.
I believe that I need to modify the following function and that I should change the code for the isDirectory check but I'm not sure if that is the correct way to go about doing this. Any suggestions would be appreciated.
StaticServlet.prototype.handleRequest = function(req, res) {
var self = this;
var path = ('./' + req.url.pathname).replace('//','/').replace(/%(..)/g, function(match, hex){
return String.fromCharCode(parseInt(hex, 16));
});
var parts = path.split('/');
if (parts[parts.length-1].charAt(0) === '.')
return self.sendForbidden_(req, res, path);
fs.stat(path, function(err, stat) {
if (err)
return self.sendMissing_(req, res, path);
if (stat.isDirectory())
return self.sendDirectory_(req, res, path);
return self.sendFile_(req, res, path);
});
}
Update #1
I have two screenshots to clarify. The first image is what I currently get, the second image is what I want.
What I Get
What I Want
Update #2
Using the link to Restify below I found the following example which is exactly what I needed.
var server = restify.createServer();
var io = socketio.listen(server);
server.get('/', function indexHTML(req, res, next) {
fs.readFile(__dirname + '/index.html', function (err, data) {
if (err) {
next(err);
return;
}
res.setHeader('Content-Type', 'text/html');
res.writeHead(200);
res.end(data);
next();
});
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
server.listen(8080, function () {
console.log('socket.io server listening at %s', server.url);
});
The angular-seed project is a starting point for the client, but not really for the server side.
They included a simple web-server node script without dependencies. This way you don't need npm or other modules.
For the server side you can use node with connect/express or any other web server/language.
You just need to make rest services and serve some static html.
Since you have already installed Node restify may be something for you.
Update: I created a basic sample for using the angular-seed with restify:
https://github.com/roelandmoors/restify-angular-seed