My index.js file is
var express = require('express');
var app = express();
var path = require('path');
var router = express.Router();
var data = require('./data/jsonData');
var createDatabase = require('./data/db');
var careateTable = require('./data/createTable');
var insert = require('./data/insert');
var bodyParser = require('body-parser');
var select = require('./data/select');
app.use(express.static(path.join(__dirname, 'www')));
app.use(express.static(path.join(__dirname, 'form')));
app.use(bodyParser());
app.get('/' , function (req , res) {
res.sendFile(path.join(__dirname + '/www/index.html'));
});
app.get('/data' ,function (req , res) {
res.json(data);
});
app.get('/form' ,function (req , res) {
res.sendFile(path.join(__dirname + '/form/index.html'));
});
app.post('/form' ,function (req , res) {
console.log(req.body.user);
console.log(req.body.password);
insert.insertModule(req.body.user , req.body.password);
res.sendFile(path.join(__dirname + '/www/index.html'));
});
app.get('/show' , function (req , res) {
var i ;
select.select( function (err, results) {
if (err == 'error') {
console.log(err);
} else {
console.log(results);
res.send(results.username);
}
});
});
app.listen(3000);
console.log("App is listning on port 3000");
and select.js is
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "NodeDataBase"
});
con.connect(function (err) {
if (err) throw err;
console.log("Connected!");
});
module.exports = {
select: function (callback) {
var sql = "SELECT username , password FROM login ";
con.query(sql, function (err, result , fields) {
if (err) {
callback("error", err)
} else {
callback("success", result)
}
});
}
}
I want to show the results object data to html file , So how can i do this please suggest me.
from a get request /show it will show all userdata fetched from the database
I´ll try to explain the way it works (with the consideration on you are now able to see the data on 'http://localhost:3000/show') . Plz, guys, correct me if I do explain something in the wrong way.
There, what you have in your code, is the
Server side code
mysql: Declares connection to database (this is your database connector)
node.js: Declares methods to put/push/get data from database (your server side as is)
express.js: Declares urls to put/push/get data from database (http/https router)
Then, if we check the code, we can see the declaration of a server api - for example app.get('/show')
There, what you are saying is that express, will use the url /show with the method GET
Here is where your client appears in scene. Now, we suppose your server is up and running, waiting to serve GET petitions on http://localhost:3000/show.
If that is correct, when clicking the link you should see the user names, and now you will need an http client to connect to your http server side.
The way you can grab data on your HTML client from your server, is javascript.
Then, you will need to build an HTML file, that will also contain a javascript script (in my example written in angular).
The HTML (this is written in jade. you can convert it) should look like this:
Client HTML Code
You should create an index.html file, and paste this code
<!doctype html>
<html ng-app>
<head>
<title>My AngularJS App</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
</head>
<body>
<div ng-controller="MyCtrl">
<table>
<thead>
<tr>
<th>
<p>Name</p>
</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="user in users">
<td>
<p>{{user}}</p>
</td>
</tr>
</tbody>
</table>
</div>
<script>
var myApp = angular.module('myApp',[]);
function MyCtrl($scope, $http) {
//This method will call your server, with the GET method and the url /show
$http.get("http://localhost:3000/show").then(function(success){
if(success.data.length>0)
{
$scope.users=success.data;
}
});
}
</script>
</body>
</html>
This code should capture the data and show a row in the table for every name in the database.
Hope it helps, at least as a clear explanation of how the full stack (client-server) works.
May be you can use view engine such As EJS, Jade to render data from node to the front end.
If you want to render the data on the html page, i will do it like http://localhost:3000/show : with json -resonponse
var express = require('express');
var app = express();
require('json-response');
app.get('/', function(req, res){
res.ok({foo: 'bar'}, 'hello world');
});
i will return json from the link and in Index.html with the help of jquery/Ajax will hit the link , retrieve the value and show it on HTML
Related
Hi I am trying to send the contents of string stored in mongo db through res.render. However, if I check after sending this string, the tag appears in the form of a string and does not appear in html, so I want to know how to solve it.
router.get("/:id", async function (req, res) {
var article = await Article.findById(req.params.id);
console.log(article);
res.setHeader("Content-type", "text/html");
res.render("articles/article", { article: article });
});
article = "<p>내용입니다.</p>"
here is the working example. You have to install the pug template engine or any other template engine. See the test. pug file and note that if the variable is HTML content then we have to use the syntax "!{para}" or if the variable is a simple string then we can use the syntax "#{para}".
so the folder structure would be like
app.js
views ->test.pug
// app.js file
var express = require('express');
var app = express();
var PORT = 3000;
app.set('view engine', 'pug');
app.use('/', function(req, res, next){
res.render('test', {para : `<p>This is paragraph</p>`});
});
app.listen(PORT, function(err){
if (err) console.log(err);
console.log("Server listening on PORT", PORT);
});
// html file test.pug
<div>!{para}</div>
I'm kind of newbie to the node.js, this might be silly one but not actually getting proper way to achieve this. here I'm trying to send the mysql result from the node.js res.send() method, here below I'm adding my code.
router.post('/get_doc_msgs', (req, res)=>{
var d_msg = "SELECT * FROM msgs WHERE d_id = ?";
var d_msgs = [req.body.doc_id_msgs];
db.query(d_msg, d_msgs, (err,rows) => {
if(err){
console.log('error ', err);
}
else{
res.send(rows)
}
});
})
and here is my function to get the data to the rendered ejs file.
function getmsgs(){
$.ajax({
type:'POST',
url: '/get_doc_msgs',
data: {
doc_id_msgs : $('#doct_id').val();
},
success: function(data){
$('#msg_q').html(data);
}
})
}
advance thank you for help and suggestions .
Here's a complete example of how this might work, I've added server and client code.
If you run
node app.js
Then go to http://localhost:3000 you should see the example working.
The main issue I believe is you need to use a body-parser in Express so you can parse uploaded data correctly. In this case I've used JSON, you could use another encoding if you wished.
The only change I made to the server code was really to add the body parser.
On the client side, I set a content-type header and used JSON.stringify() on the uploaded data.
It's not a silly question, getting all this stuff to play nice takes a little bit of practice and effort!
app.js
const mysql = require('mysql');
const express = require('express');
const app = express();
const router = app;
const port = 3000;
const bodyParser = require("body-parser");
// Add the credentials to access your database
var db = mysql.createConnection({
host : 'localhost',
user : '<user>', /* replace these with real values. */
password : '<pw>', /* replace these with real values. */
database : '<db>' /* replace these with real values. */
});
app.use(bodyParser.json());
app.use(express.static("./"));
router.post('/get_doc_msgs', (req, res)=>{
var d_msg = "SELECT * FROM msgs WHERE d_id = ?";
var d_msgs = [req.body.doc_id_msgs];
db.query(d_msg, d_msgs, (err,rows) => {
if(err){
console.log('error ', err);
} else {
res.send(rows)
}
});
})
app.listen(port);
index.html
<!DOCTYPE html>
<html>
<head>
<script
src="https://code.jquery.com/jquery-3.5.1.min.js"
integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0="
crossorigin="anonymous"></script>
</head>
<body style="padding:20px">
<label>Doc id:</label><input id="doct_id" value="1"/>
<h4>Response:</h4>
<p id="msg_q"></p>
<script>
function getmsgs() {
$.ajax({
type: 'POST',
url: '/get_doc_msgs',
contentType: "application/json",
data: JSON.stringify({
doc_id_msgs : $('#doct_id').val()
}),
dataType: "json",
success: function(data) {
for(row of data) {
$('#msg_q').append("<li>" + Object.values(row).join("\t") + "</li>");
}
}
})
}
console.log("Doc id:", $('#doct_id').val());
getmsgs();
</script>
</body>
</html>
`getDocMessg = (req, res, next) => {
mess_id = req.body.doc_id_msgs
db.execute("SELECT* FROM msgs WHERE d_id = ?", [mess_id]).then((results) => {
res to render the page you want to send the data to
res.render('name of page', {
message : results[0]
})
})
}`
something like that should do the job you need to adapt it to your website structure, using ejs you can call the variable message and show it on your page :)
This is my HTML file with Vue Js code as well:
<!DOCTYPE html>
<html>
<head>
<!-- Vue development version, includes helpful console warnings -->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<!-- Axios library -->
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<div id="app">
<table>
<thead>
<tr>
<th>name</th>
<th>description</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<tr v-for="game in games">
<td>{{game.Name}}</td>
<td>{{game.Description}}</td>
<td>{{game.price}}</td>
</tr>
</tbody>
</table>
</div>
<script>
const app = new Vue({
el: '#app',
data: {
games: []
},
methods : {
//get all the products from the web service using Axios
loadAllProducts: function(){
var localApp = this;
axios.get('/finalgame') //send GET request to games path
.then(function (response){
//returned array of games
localApp.games = response.data.data;
console.log(JSON.stringify(response.data.data));
})
.catch(function (error){
//handle error
console.log(error);
});
}
},
created: function(){
this.loadAllProducts();
//refreshes every 5 seconds
setInterval(this.loadAllProducts, 4000);
}
})
</script>
My Node JS server.js file:
//Import the express and url modules
var express = require('express');
var url = require("url");
//Status codes defined in external file
require('./http_status');
//The express module is a function. When it is executed it returns an app object
var app = express();
//Import the mysql module
var mysql = require('mysql');
//use index html page
app.use(express.static('./public'))
//Start the app listening on port 8080
app.listen(8080);
//Create a connection object with the user details
var connectionPool = mysql.createPool({
connectionLimit: 10,
host: "localhost",
user: "root",
password: "",
database: "pricen",
debug: false
});
app.get('/messages', (req, res) => {
console.log("show messages")
res.end()
})
app.get('/index.html', (req, res) =>{
res.sendFile(__dirname + '/index.html');
})
//URL to get all game products with price
app.get('/finalgame', (req, res) => {
console.log("Fetching game product with prices by joining table: " + req.params.id)
const sqlquery = "SELECT name, description, price FROM game" + " INNER JOIN price ON game.id = game_id"
connectionPool.query(sqlquery, (err, rows, fields) => {
console.log("user success!")
res.json(rows)
})
})
When you go to localhost:8080/finalgame gives you this data:
[{"name":"Fifa 19...","description":"Fifa 19 game","price":29.85},
{"name":"Fifa 20...","description":"Fifa 20 game","price":29.85},
{"name":"name":"Far Cry 4...","description":"Far Cry 4...","price":14.85}]
I want to display this JSON data into my table row by row using vue js because apparently it's easy to use compare it to HTTPRequest using AJAX.
The output I get when I go to the localhost:8080/index.html:
name description Price
I am stuck on this for days now. Please help.
If what you get returned, looks like...
[{"name":"Fifa 19...","description":"Fifa 19 game","price":29.85}.....]
it means that there is no data property, but what you get is an array. So try:
.then(function (response){
// remove the extra 'data'
localApp.games = response.data;
console.log(JSON.stringify(response.data));
})
Then as in other answer, check the casing. You have lowercase in your response, so should be
{{ game.name }} and {{game.description}}
Check the casing. The response returns [{"name": "..."}] and your Vue template shows {{game.Name}}.
It should be {{game.name}}
I am struggling to output the data from MySQL into my HTML page. I need suggestions on how I can extract data from MySQL and display it on my HTML page. As you can see below, the server code connects to the HTML page and MySQL, but I just need to input the MySQL data into the HTML div.
index.html
<!DOCTYPE>
<html>
<head>
<title>Data from MySQL</title>
</head>
<body>
<div id="output_message"></div>
</body>
</html>
app.js
var express = require('express');
var app = express();
var mysql = require('mysql');
var bodyParser = require('body-parser');
var urlencodedParser = bodyParser.urlencoded({ extended: false });
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use('/', express.static(__dirname + '/'));
var connection = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "mywebsite"
});
connection.connect();
app.get('/', function(req, res) {
connection.query("SELECT * FROM chat", function(err, result) {
if(err) throw err;
console.log(result);
res.send(JSON.stringify(result[0].Message));
});
res.sendFile(__dirname + '/index.html');
});
app.listen(3000, function () {
console.log('Connected to port 3000');
});
Dependind on your needs :
· Server Renders Data :
You will be needing a view engine such as hbs
(as Robert Moskal stated in a comment to your question, it is very clearly explained)
· Client Renders Data :
You will need to :
1] extract the db query from the app.get("/") and make it part of the
logic in app.post("/")
app.get("/",(req, res)=>{res.sendFile(__dirname+"/index.html")})
app.post('/',(req, res)=>{
connection.query("SELECT * FROM chat",(err, result)=>{
if(err){console.log(err); res.json({"error":true}) }
else{ console.log(result); res.json(result) }
})
})
2] make a POST request from your client to the new router's post path.
3] receive the response at the client and manipulate the DOM to display the data.
Here you can find an example of sending a post request and receiving the response
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>