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
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 working with Express.js and mysql package to create my apis, but i can't make a post.
This is my code so far:
const express = require('express');
const mysql = require('mysql');
const config = mysql.createConnection({
host: theHost,
port: thePort,
user: theUser,
password: thePass,
database: theDB,
});
const app = express();
config.connect(function(err){
if(!err) {
console.log("Success");
} else {
console.log("Error trying to connect");
}
});
app.get("/api/InternalAccess", function(req, res){
config.query('SELECT * from InternalAccess', (error, result) => {
if (error) throw error;
res.send(result);
});
});
app.post("/api/internalAccess", function(req, res){
var info = { User: req.body.User, Password: req.body.Password, CreationDate: req.body.CreationDate };
config.query('INSERT INTO InternalAccess SET ?', info, (error, result) => {
if (error) throw error;
res.send(result);
});
});
app.listen(3000);
I have no problems with get, it works fine, but to make post from postman, i get the error: " Cannot read property "User" of undefined". Am i avoiding something? I'm really new using mysql package.
My db is MySQL Workbench, and as i said, i'm using Node.js, Express.js and mysql package.
Hope you can help me. Thanks in advance
In order to have req.body populated automatically, you have to use some body-parser middlewares, like:
app.use(express.json()) // for parsing application/json
app.use(express.urlencoded({ extended: true })) // for parsing application/x-www-form-urlencoded
Of course, there can be multiple other causes (like, you're not constructing the request properly in postman), but the lack of setting the middlewares is the first place I'd fix.
Seems like req.body is null. I think you might just be missing the body-parser in your app.js.
var bodyParser = require('body-parser');
var app = express();
// parse application/json
app.use(bodyParser.json())
see other examples here: https://expressjs.com/en/resources/middleware/body-parser.html
I need display data in table from MySql database, but I dont know how it do this.
I tried found something example or example application with source code, but I nothing found.
Maybe someone help me with this?
I tried with node.js express:
var mysql = require('mysql');
var https = require('https');
var con = mysql.createConnection({
host: "https://adress to database",
user: "user",
password: "password",
database: "db"
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
});
But i get error:
Error: getaddrinfo ENOTFOUND
here is a simple way to get data from mySQL and export it as json:
var http = require('http');
var mysql = require('mysql');
var bodyParser = require("body-parser");
var express = require('express');
var app = express();
var pool = mysql.createPool({
host: 'db location',
user: 'username od db',
password: 'something',
database: 'yourdatabase',
port:3306
});
// define rute
var apiRoutes = express.Router();
var port = 9000;
apiRoutes.get('/', function (req, res) {
res.json({ message: 'API works' });
});
apiRoutes.get('/data', function (req, res, next) {
pool.getConnection(function (err, connection) {
if (err) {
console.error("error hapened: " + err);
}
var query = "SELECT * FROM imena ORDER BY id ASC";
var table = ["imena"];
query = mysql.format(query, table);
connection.query(query, function (err, rows) {
connection.release();
if (err) {
return next(err);
} else {
res.json({
success: true,
list_users: rows
});
}
});
});
});
app.use('/api', apiRoutes);
// starting
app.listen(port);
console.log('API radi # port:' + ' ' + port);
But i still suggest that you start using noSQL databases like firebase because of they are simple and faster.
In order to show data from MySQL Database, you need to provide application interface(s) to Angular environment and only then Angular can use the data. There are few techniques in which you can design interfaces, REST is the most popular though.
First you need to understand that Angular is Front-End framework and it can only send requests to backend such as Node js, PHP etc.Thus, first you need to chose your backend. Node is popular with express js module, but if you still don't have mySQL set, go for firebase real time database. If you decide node js => express => mySQL check tutorial online.
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
I just started to learn nodejs with express framework.In my app there are two pages app.js and db.js..I need to post data from form and insert to register table
In db.js
var mysql = require('./node_modules/mysql');
var connection = mysql.createConnection({
host: '127.0.0.1',
user: 'root',
password: '',
database: 'nodeapp'
});
connection.connect(function (err) {
if (err)
throw err;
});
module.exports = connection;
// In my app.js page
var express = require('./lib/express');
var app = express();
var bodyParser = require('body-parser')
var db = require('/db');
app.get('/', function (req, res) {
res.sendFile('/NodeProj/views/' + 'index.html');
});
/** bodyParser.urlencoded(options)
* Parses the text as URL encoded data (which is how browsers tend to send form data from regular forms set to POST)
* and exposes the resulting object (containing the keys and values) on req.body
*/
app.use(bodyParser.urlencoded({
extended: true
}));
/**bodyParser.json(options)
* Parses the text as JSON and exposes the resulting object on req.body.
*/
app.use(bodyParser.json());
app.post('/process_form', function (req, res) {
var response = {
"firstname": req.body.fst_name,
"email": req.body.fst_email,
"password": req.body.fst_password
};
var query = connection.query('INSERT INTO register SET?',response,function(err,result){
if(err) throw err;
if(result) console.log(result);
});
res.end(JSON.stringify(response));
});
app.listen(8081);
But when I run the code I got the following error
Refference error: connection is not defined
Please help me .Thanks in advance.
As mentioned in the comments, you've called connection db.
So if you replace var db = require('/db'); with var connection = require('./db'); then your connection will be defined.