问题描述
我是node.js的新手,正在尝试从服务器端js调用ejs文件。我正在从客户端js文件中调用post和get方法。下面是我的代码。
客户端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',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();
});
}) ;
我尝试了多种方法来渲染FantasyTeam.ejs文件。但是无法成功,代码中没有错误,只是不重载ejs文件。感谢这方面的帮助。
解决方法
首先,您已在节点应用程序上设置了视图引擎。然后,第二步在应用程序根目录上创建一个views文件夹,然后在views文件夹中创建一个pages文件夹,然后在您的pages文件夹中创建所有模板。 views文件夹必须是静态的。最后,您可以从views目录中的pages文件夹渲染模板。看我的例子。有关更多信息,请访问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})
})