I am new to NodeJS and Express (to coding, in general). I am trying to render data to an EJS view page so I can manipulate it in the front end. It looks something like this:
app.set('view engine','ejs');
var str = JSON.parse('[{"name":"bill", "age":"26"}, {"name":"jeff", "age":"32"}]');
str.forEach(function(data){
console.log(data.name);
});
app.get('/data', function(req, res){
res.render('data', {str:str});
});
I try to test it in the EJS file by typing in <%= data %> the output I am getting in the browser is [object Object],[object Object]. I feel like I am missing a few piece. Can someone please help me out?
Thanks
Edit:
Thanks Booligoosh. Just want to add that I had to convert it back to JSON in the EJS side afterward to make it work. :)
You are attempting to print an array containing two objects to the ejs template. In a template you only print strings.
To print an object to the template we first need to stringify it:
<%= JSON.stringify(str) %>
To access a property of the object in your array we reference the array index and the property key:
<%= str[0].name %>
To iterate over the array and print out all the values we use a forEach:
<ul>
<% str.forEach(function(o) { %>
<li><%= o.name %> - <%= o.age %></li>
<% }); %>
</ul>
In ejs template we can render json object as below:
<%- JSON.stringify(user) %>
I tried with <%= JSON.stringify(user) %> (<%=) but it will print asci code values for double-quotes.
Try this:
app.set('view engine','ejs');
var str = JSON.parse('[{"name":"bill", "age":"26"}, {"name":"jeff", "age":"32"}]');
str.forEach(function(data){
console.log(data.name);
});
app.get('/data', function(req, res){
res.render('data', {str: JSON.stringify(str) });
});
You will need to convert your JSON object back to a string before passing it to the template using JSON.stringify, otherwise it will just be rendered with .toString, which returns [object Object],[object Object].
Related
I have a select form which determines which values are shown in a table. The values are stored in a json file. My Question is: what is the best way to do this cuz i have a gut feeling smth might be wrong with my solution.
Im able to open the json file and save it in a json/jbuilder object in my controller and then call the object in my view and pass the json in the select which calls a stimulus function, which then handles what is shown on the table.
Main Controller:
class MainController < ApplicationController
def index
#itemsJSON = JSON.parse(File.read('db/data.json'))
end
end
Index View
<%= form_with do |form| %>
<%= form.select :city, [['all'], ['critical'],['error'],['warning'],['info'],['debug']],
{ prompt: "Select Item Type" },
data: { controller: "dropdownTable", value: #itemsJSON,
action: "change >dropdownTable#selectData"} %>
<% end %>
Stimulus Function
Code that doesnt work gives back error: localhost:8080/main/db/database.json not found which // i dont understand why
//fetch('/db/data.json')
// .then((response) => response.json())
// .then((json) => console.log(json));
export default class extends Controller {
selectData(event){
... code that works
}
}
I have a use case where an object was passed from server to client through EJS like below:
res.render('mytemplate', {data: myobject});
<script type='text/javascript'>
<% if (typeof data !== 'undefined' && data) { %>
data: '<%= JSON.stringify(data) %>',
<% } %>
</script>
I'm having this issue that in the client code, the returned stringified object looks like
{"key":"value"}
whereas it is supposed to be
{"key":"value"}
So when I do JSON.parse() in the client code I get an error. How do I keep the quotation marks in the string instead of the special character code? Thanks!
I think you need to use the unescaped way in your template:
data: '<%- JSON.stringify(data) %>',
Note the <%- instead of <%=
See the documentation "Tags" section: https://ejs.co/#docs
I want to get data from this JSON file: https://restcountries.com/v3.1/name/Poland into a EJS variable 'userData' and show it on the screen. How can I get it done?
I tried:
<%
const userData = require('https://restcountries.com/v3.1/name/Poland');
%>
<%= JSON.stringify(userData) %>
i tried to pass a data from js file(sample.js) to ejs using res.send("filename.ejs",data) by converting a object into JSON where JSON data is displaying on console, but while trying to pass it showing an error
TypeError: Cannot create property '_locals' on string
can some one help with this and tell me how to call them in ejs file
res.send() is used for send data there is no need to point ejs file
res.send takes array as parameter (res.send([body])) and you can get it in ejs like {{ data }}
for example
NODEJS
res.send({message: 'hello'})
filename.ejs
<div>{{ message }}</div> or <%= JSON.stringify(message) %>
also as Express 5x does not support res.send() method you can use
res.status(200).send({message: 'hello})
(you did not admit you express version)
Note that you should not use the .ejs extension in res.render, despite other answers to your question suggesting that you do so.
When you call res.render('myView'), ejs looks for a template called myView.ejs in a folder called views (which is set as the default folder to use by ejs)
for example:
res.render('myView.ejs',{
data:data,
foo:'foo'
});
ejs will look for a view called myView.ejs.ejs (or it might just fail alltogether).
To access the data on your template, you would do the following:
app.js:
app.get('/somePathHere', function(req, res) {
res.render('myView',{
data:data,
foo:'foo'
});
});
myView.ejs:
<% data.forEach(function(item) { %>
//do something
<% }); %>
<%= foo %>
Note that when accessing a variable, you use the <%= varNameHere %>, and when writing any type of function, you would omit the =.
You're sending data to your view so update your code with this and try
res.render("filename",{
data:"hello"
});
Or you can pass whole data
res.render("filename",{data:data});
And in your ejs file access it like this
<div> <%= data %> <div>
my function "fus.listjson" that generate json data i wants to send specific html page.So i perform such operation, how can i solve this problem.
app.get('/list/json',fus.listjson);
currently i used socket connection. I does not want to use socket connection any other methods in node.js to handle this task.
socket.emit('ffusdata', { fusdata: fus.listjson});
plz help
how do i go above this.
thank's in advance
You want to render the JSON as part of a HTML page with other content? You're going to need a template engine with your express application.
EJS is decent (https://github.com/visionmedia/ejs) as is Jade. I've included a sample of EJS below.
app.get('/', function(req, res) {
res.render('xyz', {
jsondata: YOUR_JSON
});
});
// xyz.ejs
<% if (jsondata) { %>
<pre><%= jsondata %></pre>
<% } %>
I assume you are using express, since you have app.get. In that case just use the json method on the response object:
app.get("/list/json", function(req, res) {
res.json(fus.listjson);
});