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>
Related
I am new on Node.js and I have app.js file like:
const express = require('express');
const app = express();
const port = 8080;
app.get('/', (req, res) => res.send('Hello World'));
app.listen(port);
console.log(`App running on http://localhost:${port}`);
I also have index.html file in the same folder with app.js. Here there is a HTML5 website.
When I run the project I can see Hello World text in browser, How can I show this HTML file from my app.js so when I deploy it, it should show me responsive HTML file instead of Hello World?
I tried
app.get('/',function(req,res) {
res.sendFile('index.html');
});
But didn't see a difference.
To make your code example work you'll need to specify an absolute path, try using this:
res.sendFile(__dirname + "/index.html");
Another way would be to use EJS (https://ejs.co/)
In your example, you could do the following:
Install EJS:
npm install ejs
Set the View Engine to EJS:
app.set('view engine', 'ejs')
- Move your index.html file to a folder called "views" and also rename the file to index.ejs
views/index.ejs
In your app.get() handler, use:
res.render('index')
Final Result:
const express = require("express");
const app = express();
app.set("view engine", "ejs");
const port = 8080;
app.get("/", (req, res) => {
res.render("index");
});
app.listen(port, () => {
console.log(`App running on http://localhost:${port}`);
});
(note: I also moved your console.log to inside app.listen)
I found this on another stack overflow question, it should work
fs.readFile(__dirname + '/views/test.html', 'utf8', function(err, text){
res.send(text);
});
I've built few pages of a static website using ExpressJS and PUG to get the advantage of the template engine.
But now I need to export all the raw HTML that is being rendered by all ExpressJS Routes.
Is there any package that can help me to do that? Or I've to write custom command and iterate over all the Routes and save the rendered output?
If a custom command is the only way, how do I iterate over all the routes and get the rendered output?
I couldn't find any library or resource to achieve what I wanted. But with some of my dirty code, hacks, and packages I was able to export all the routes.
Note: Instead of writing a node command to export the htmls, I've added a route to trigger the operations here is the code for the route:
app.use('/export_templates', router.get('/', async function (req, res, next) {
const endpoints = listEndpoints(app);
const failedEndpoints = [];
for (const i in endpoints) {
const endpoint = endpoints[i];
if (endpoint.path == '/export_templates') {
continue;
}
try {
const res = await axios.get('http://'+req.headers.host+''+endpoint.path+'?export=true');
}
catch(error) {
failedEndpoints.push(endpoint.path);
}
}
res.json({
"status": "succes",
"message": "Please check templates folder for the latest exported html templates",
"failed": failedEndpoints
})
}));
Basically this route iterates and makes a request to all the available routes with a export=true parameter.
Then inside every route view function a condition checks if the export parameter is available then calls the exportTemplateFile function with the pug template location and new file name as the function parameter.
If the request doesn't contain export parameter the requested route will simply output what template.
An example route:
router.get('/', function(req, res, next) {
if (req.query.export) {
exportTemplateFile('views/index.pug', 'index.html');
}
res.render('index.pug');
});
And here is the code for 2 util function to complete the export process
function createTemplateFile(filename) {
fs.open(filename,'r',function(err, fd){
if (err) {
fs.writeFile(filename, '', function(err) {
if(err) {
console.log(err);
}
});
}
});
}
function exportTemplateFile(templateLocation, templateName) {
const html = pretty(pug.renderFile(templateLocation));
createTemplateFile('templates/'+templateName);
var stream = fs.createWriteStream('templates/'+templateName);
stream.once('open', function (fd) {
stream.write(html);
stream.end();
});
}
The createTemplateFile function simply creates a new file if it doesn't exist.
The exportTemplateFile function saves the HTML in the html variable rendered by pug and prettifies it with the pretty package and then overwrites the new template file.
Note: In my case all the pug templates were static so I didn't have to pass any context to the pug.renderFile function. But if you need any context to be used inside the pug template you can simply pass that with the template location.
Edited version of the same answer.
First of all thank you so much for solving this problem.
I have made some changes to your code as per new errors.
Here is the code with async and await function for ejs users
const express = require('express')
const ejs = require('ejs')
const fs = require('fs')
const app = express()
const port = 3000
//set the templating engine as ejs
app.set('view engine', 'ejs');
function createTemplateFile(filename) {
fs.open(filename,'r',function(err, fd){
if (err) {
fs.writeFile(filename, '', function(err) {
if(err) {
console.log(err);
}
});
}
});
}
async function exportTemplateFile(templateLocation, templateName) {
var html = await ejs.renderFile(templateLocation);
createTemplateFile('templates/'+templateName);
var stream = fs.createWriteStream('templates/'+templateName);
stream.once('open', function (fd) {
stream.write(`${html}`);
stream.end();
});
}
app.get('/', (req, res, next) => {
res.render('./pages/home')
exportTemplateFile('views/pages/home.ejs', 'index.html');
console.log('file rendered and saved successfully')
})
app.listen(port, () => {
console.log(`App is listening on port ${port}`)
})
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
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'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>