EJS, body parser - vijayetar/seattle-301d55 GitHub Wiki
Use this to send information from the front to the backend and back. Use body-parser to make it secure
//
app.use(express.static('./public'); //app.set('view engine', 'ejs');// app.use(express.urlencoded({extended:true}));
// routes for home page
// app.get('/', getHomePage);
function getHomePage(request,response){ response.status(200).render('index');
}
app.get('/searches/new', displaySearch);
function displaySearch(request,response) { response.status(200).render('./pages/searches/new.ejs');
}
app.post('/searches/new', collectBook);
function collectBook(request, response) {
console.log(request.body);
let searchWord = request.body.search[0];
let searchType = request.body.search[1];
let url = '';
if (searchType === 'title') { url +=
intitle:${searchWord}} else { url += inauthor:${searchWord}}superagent.get(url).then(agentResults => { let bookArray = agentResults.body.items; const betterBookArray =
bookArray.map(book => new Book(book.volumeInfo); respond.send(200).render)})
function Book(obj) { const placeholderImage = 'https://i.imgur.com/J5LVHEL.jpg'; this.title = info.title || 'No title available';}
}
}
// app.post('/contact, (request,response) => {
// console.log(request.body);
// response.sendFiel('./thanks.html', {root:'./public'});
// })
For applications that need quick templating, there are many options that we can use. EJS is one of them
these are the docs
this is for fun
Use this to get more information on EJS template.
var expressLayouts = require('express-ejs-layouts'); app.use(expressLayouts);
install Cors, express, body parser, path (joins two paths) npm install --S express-ejs-layouts
npm install -S express body-parser cors ejs
app.use(express.urlencoded({extended:true})); CAN BE USED INSTEAD
app.use(bodyParser()); app.use('cors');
app.set('views', path.join(_dir_name,'views')); app.set('view engine','ejs)
This is the home page: app.get('/', function (request,response) { response.status(200).render('index.ejs');});
This is the list: app.get('/list), (request, response) { response.status(200).render('list.ejs', {keynameOfArray: globalvariable}); )
You have to use <%=myFavoriteFood%> in the list.ejs file.
Or another way <% keyNameForArr.forEach((food => {%><%= food %> <% }) %>
response.render ===> takes in string of the file name, object of the local variables, which could include arrays, and then the call back
in index.ejs use ejs tags to create html type page.
So to create a loop, use ejs tags to make a for loop in the index.ejs file, and then maketags with ejs injected variable just once, and the for loop with interate over the object with the arrays in it as key[value] pair and then render it on the front page.
the layouts.ejs is your wrapper and stays consistent.
create partials in the server.js and then iinject it into the layout.ejs by saying include('partials(folder)/file path').
app.listen(8000....)