0

I am unable to render data in html template but when I use express then inserted but file format is ejs . but I need listing my data in html without express. How to do that?

This is my server.js file here I have in this file database connection, insert record, select record and edit record query. Please see my code here is sjs templates.

Note: the problem is here is ejs templates but I want to render my nodejs code in .html format file not .ejs format.

server.js

var express  = require('express'),
path     = require('path'),
bodyParser = require('body-parser'),
emailExistence = require('email-existence'),
app = express(),
expressValidator = require('express-validator');


/*Set EJS template Engine*/
app.set('views','./views');
app.set('view engine','ejs');

app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser.urlencoded({ extended: true })); //support x-www-form-urlencoded
app.use(bodyParser.json());
app.use(expressValidator());

/*MySql connection*/
var connection  = require('express-myconnection'),
mysql = require('mysql');

app.use(

connection(mysql,{
    host     : 'localhost',
    user     : 'root',
    password : '',
    database : 'mydb',
    debug    : false //set true if you wanna see debug logger
},'request')

);

app.get('/',function(req,res){
    res.send('Welcome');
});


//RESTful route
var router = express.Router();


/*------------------------------------------------------
*  This is router middleware,invoked everytime
*  we hit url /api and anything after /api
*  like /api/user , /api/user/7
*  we can use this for doing validation,authetication
*  for every route started with /api
--------------------------------------------------------*/
router.use(function(req, res, next) {
    console.log(req.method, req.url);
    next();
});

var curut = router.route('/user');




//show the CRUD interface | GET
curut.get(function(req,res,next){


    req.getConnection(function(err,conn){

        if (err) return next("Cannot Connect");

        var query = conn.query('SELECT * FROM t_user',function(err,rows){

        if(err){
            console.log(err);
            return next("Mysql error, check your query");
        }

        res.render('user',{title:"RESTful Crud Example",data:rows});

        });

    });

});


//post data to DB | POST
curut.post(function(req,res,next){

    //validation
    req.assert('name','Name is required').notEmpty();
    req.assert('email','A valid email is required').isEmail();
    req.assert('password','Enter a password 6 - 20').len(6,20);

    var errors = req.validationErrors();
    if(errors){
        res.status(422).json(errors);
        return;
    }
   
    //get data
    var data = {
        name:req.body.name,
        email:req.body.email,
        password:req.body.password
    };
    //inserting into mysql
    req.getConnection(function (err, conn){

        if (err) return next("Cannot Connect");

        var query = conn.query("INSERT INTO t_user set ? ",data, function(err, rows){

        if(err){
        console.log(err);
        return next("Mysql error, check your query");
        }

        res.sendStatus(200);

        });

    });

});


//now for Single route (GET,DELETE,PUT)
var curut2 = router.route('/user/:user_id');

/*------------------------------------------------------
route.all is extremely useful. you can use it to do
stuffs for specific routes. for example you need to do
a validation everytime route /api/user/:user_id it hit.

remove curut2.all() if you dont want it
------------------------------------------------------*/
curut2.all(function(req,res,next){
console.log("You need to smth about curut2 Route ? Do it here");
console.log(req.params);
next();
});

//get data to update
curut2.get(function(req,res,next){

    var user_id = req.params.user_id;

    req.getConnection(function(err,conn){

        if (err) return next("Cannot Connect");

        var query = conn.query("SELECT * FROM t_user WHERE user_id = ? ",[user_id],function(err,rows){

        if(err){
            console.log(err);
            return next("Mysql error, check your query");
        }

        //if user not found
        if(rows.length < 1)
            return res.send("User Not found");
            res.render('edit',{title:"Edit user",data:rows});
        });

    });

});

//update data
curut2.put(function(req,res,next){
    var user_id = req.params.user_id;

    //validation
    req.assert('name','Name is required').notEmpty();
    req.assert('email','A valid email is required').isEmail();
    req.assert('password','Enter a password 6 - 20').len(6,20);

    var errors = req.validationErrors();
    if(errors){
        res.status(422).json(errors);
        return;
    }

    //get data
    var data = {
        name:req.body.name,
        email:req.body.email,
        password:req.body.password
    };

    //inserting into mysql
    req.getConnection(function (err, conn){

        if (err) return next("Cannot Connect");

        var query = conn.query("UPDATE t_user set ? WHERE user_id = ? ",[data,user_id], function(err, rows){

        if(err){
        console.log(err);
        return next("Mysql error, check your query");
        }

        res.sendStatus(200);

        });

    });

});

//delete data
curut2.delete(function(req,res,next){

var user_id = req.params.user_id;

req.getConnection(function (err, conn) {

    if (err) return next("Cannot Connect");

    var query = conn.query("DELETE FROM t_user  WHERE user_id = ? ",[user_id], function(err, rows){

    if(err){
    console.log(err);
    return next("Mysql error, check your query");
    }

    res.sendStatus(200);

    });
    //console.log(query.sql);

    });
});

//now we need to apply our router here
app.use('/api', router);

//start Server
var server = app.listen(4000,function(){

console.log("Listening to port %s",server.address().port);

});

user.ejs This is my ejs view template files

<!DOCTYPE html>
<html>
    <head>
        <title><%=title%></title>
        <script type="text/javascript" src="/../js/jquery-1.10.2.min.js"></script>
        <script type="text/javascript" src="/../js/all.js"></script>
        <link rel="stylesheet" href="/../css/style.css">
    </head>
<body>
<div class="data-table">
    <table border="1" cellpadding="7" cellspacing="7">
        <tr>
            <th width="50px">No</th>
            <th>Name</th>
            <th>Email</th>
            <th>Password</th>
            <th>Action</th>
        </tr>
                       
        <% if(data.length){ 
                        
         for(var i = 0;i < data.length;i++) { %>
         
        <tr>
            <td><%=(i+1)%></td>
            <td><%=data[i].name%></td>
            <td><%=data[i].email%></td>
            <td><%=data[i].password%></td>
            <td>
                <a class="a-inside edit" href="/api/user/<%=data[i].user_id%>">Edit</a>
               
                <a class="a-inside delete" href="javascript:void(0)" onClick="deleteUser(<%=data[i].user_id%>)">Delete</a>
               
            </td>
        </tr>
    <% }
    
     }else{ %>
         <tr>
            <td colspan="5">No Data</td>
         </tr>
    <% } %>
                                      
    </table>
</div>
<div class="page-data">
    
    <form method="post" action="" id="the-form">
        <table cellpadding="11">
        <tr>
            <td class="label">Name</td><td>: <input type="text" name="name"></td>
         </tr>
        <tr>
            <td class="label">Email</td><td>: <input type="text" name="email"></td>
         </tr>
          <tr>
            <td class="label">Password</td><td>: <input type="password" name="password"></td>
         </tr>
         <tr>
            <td class="label"></td>
            <td>
                &nbsp; <input type="button" value="Save" onClick="saveUser()">
            </td>
         </tr>
        </table>
    </form>
</div>
<div class="page-data">
     <ul class="err-area"></ul>
</div>

<script>

    function saveUser(){
       
       $.ajax({
        
        url:"/api/user",
        type:"post",
        data:$("#the-form").serialize(),
        success:function(res){
            
            window.location.reload();
            return false;
        },
        error:function(xhr, status, error){
            
            console.log(xhr.responseText);
            var err = '';
            $.each(JSON.parse(xhr.responseText) , function(i, item) {
               
                 err +='<li>'+item.msg+'</li>';
            });
            $(".err-area").html(err);    
            return false;
        }
        
       });
    }
    
    function deleteUser(user_id){
    
        $.ajax({
            url:"/api/user/"+user_id,
            type: 'DELETE',
            success: function(res) {
                
                window.location.reload();
                return false;
            },
            error:function(xhr, status, error){
            
                console.log(xhr.responseText);
                alert("Error deleting");
                return false;
            }
        });
    }

</script>
</body>
</html>

3
  • 1
    please provide the code you've done Commented Apr 25, 2018 at 5:55
  • @AmirHosseinRd I have added my code please look at my code Commented Apr 25, 2018 at 6:29
  • Check the doc expressjs.com/en/4x/api.html#res.render Commented Apr 25, 2018 at 7:09

1 Answer 1

1

All you need is res.render("path to ejs file", {variables...}) to convert the ejs template to HTML response.

app.set('views','./views');
app.set('view engine','ejs');

This part takes care of the rendering HTML.

Sign up to request clarification or add additional context in comments.

2 Comments

I don't want to render in ejs template I want to render my code in html
If you want to send a static html file, you can use. app.get('/',function(req,res){ res.sendFile('index.html'); });

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.