Reputation: 159
I've got a NodeJS Express back-end.
When it receives a GET request to the route /messages/
, it fetches the messages in the database, builds an array called messageList
and populate the view, which is then rendered to the user with no problem.
Here's the code that handles the resquest, in the Express router messages.js
:
router.get('/', async (req, res) => {
const messageList = await req.app.get('messageHandler').get();
res.render('messages', { messageList: messageList });
});
And here is part the view template in the messages.ejs
file:
<table>
<% for (var i = 0; i < messageList.length; i++) { %>
<tr id="msg-<%= i %>"><td><%= messageList[i].title %></td></tr>
<% } %>
<table>
It all works perfectly fine and smooth.
However, I'd like to eventually handle these messages in the front-end side javascript, to apply a filter by suppressing the <tr>
with a given id
property.
Is there a way to pass the array messageList
to the front-end javascript, or to load it as a javascript array when the page is loaded??
Thanks in advance! =)
Upvotes: 0
Views: 457
Reputation: 459
@Vinas from one of your comment
@OrAssayag Yes, but on the back-end part. I want to have a copy of it on the front end, so I can handle i
and
@GabrielLupu Let's say I implement a search field where the user can input the value he/she's looking for... I want to do it in the front-end, without having to make a new http request for it to be applied
You want the application response to handle res.render() & res.json()
which would throw an error so why not write another get route
like this
router.get('/', async (req, res) => {
const messageList = await req.app.get('messageHandler').get();
res.render('messages', { messageList: messageList });
});
router.get('/api', async (req, res) => {
const messageList = await req.app.get('messageHandler').get();
res.json( messageList );
});
then its look something like this on the client
<table>
<% for (var i = 0; i < messageList.length; i++) { %>
<tr id="msg-<%= i %>"><td><%= messageList[i].title %></td></tr>
<% } %>
<table>
<script>
fetch('/api')
.then(response => response.json())
.then(data => console.log(data));
</script>
Upvotes: 1