简体   繁体   中英

ejs file not rendering with res.render when I call the server side js method from client side js

I am new to node.js and trying to call an ejs file from server-side js. I am calling both the post and get methods from the client js file. Below is my code.

Client-side js:

function playerlist(){
const button = document.getElementById('playerselection');
//const data={selectedplayers:window.players};
button.addEventListener('click', function() {
  
  console.log(players);
  fetch('/FantasyTeam', {method: 'POST',
    body: JSON.stringify(players),
    headers: {'Content-Type':'application/json'},
    })
    .then(function(response) {
      if(response.ok) {
        CallGetMethod();
        return;
      }
      throw new Error('Request failed.');
    })
    .catch(function(error) {
      console.log(error);
    });
});
}
function CallGetMethod(){

  console.log('Inside CallGetMethod');
  fetch('/FantasyTeam', {method: 'GET'})
    .then(function(response) {
      if(response.ok) {
          console.log('Inside response');
          return ;
      }
      
      throw new Error('Request failed.');
    })
    .catch(function(error) {
      console.log(error);
    });
  
}


**Server-side js:**
app.post('/FantasyTeam', (req, res) => {
  
  const playerlist = req.body;
  console.log(playerlist);
    
    sql.connect(dbConfig, {
            useNewUrlParser: true
        }).then(() => {
             // create Request object
         console.log("Connected!");  
         
        var request = new sql.Request();
        
        //Insert query to FantasyTeam Table with selected players.         
        request.query("INSERT Query").then(function (err, result)
        {
            console.log('record added to db');  
            
         }).catch(err => {
            console.log('Could not insert the record to DB. Exiting now...', err);
            process.exit();
        });
        }
        res.sendStatus(201);
        
        }).catch(err => {
            console.log('Could not connect to the database. Exiting now...', err);
            process.exit();
        });
         
});

app.get('/FantasyTeam', (req, res) => {
  // connect to your database
    sql.connect(dbConfig, {
            useNewUrlParser: true
        }).then(() => {
             // create Request object
        var request = new sql.Request();
        request.query("select query"), function (err, result) 
        {    
            console.log('records fetched from DB'); 
            //res.send(result);
            //res.render(path.resolve(__dirname + "/views/FantasyTeam"),{result});
            res.render('FantasyTeam.ejs', { result });
            //res.render('FantasyTeam.ejs', { result });
            console.log(result.recordset.length);
         });
        }).catch(err => {
            console.log('Could not connect to the database. Exiting now...', err);
            process.exit();
        });
  
})  ;

I tried multiple ways to render the FantasyTeam.ejs file. But couldn't succeed.There is no error in code, except that ejs file is not redered. Appreciate any help in this regard.

At first you have set view engine on your node application. Then second step create a views folder on the application root and then create a pages folder in views folder then create all template in your pages folder. views folder needs to be static. finally you can render template from pages folder in views directory. See my example. For more information visit to ejs doc: https://ejs.co/#docs

const express = require('express');
const app = express()

const router = express.Router()

// Setup View Engine and set static folder

app.use(express.static('public'))
app.set('view engine','ejs')
app.set('views','views')

//Controller
router.get('/example',(req,res,next)=>{
  res.render('pages/index.ejs',{You Data})
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM