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>
Related
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 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].
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);
});
Can you include JSON-like data in a response using connect/express?
When users hit '/' i want to respond with all the assets but also if they are logged in I'd like to send a user object with this payload. Is this possible or do I need to make another request afterwards from the client??
You could use Express' dynamicHelpers, or perhaps helpers: http://expressjs.com/guide.html#app.dynamichelpers()
Something like this, in your app:
app.dynamicHelpers({
user: function(req, res) {
return req.session.user;
}
});
In your view:
<head>
<!-- ... -->
<script>
var user = <%- JSON.stringify(user) %>;
</script>
<!-- ... -->
Or, you could take a look at the Express expose module, which is made for this purpose!
I have two files. .rb (with Ruby code) and .erb(HTML file with some ruby script). I am calling a Ruby function in .rb from .erb.
.erb
Click here
.rb
def showProducts(param)
//Some code
end
I am able to call a function without passing parameters to it. But as and when I pass parameters to function and then call it, I receive an error. I know this is the incorrect way to call a parametrized function from .erb. What is the correct way of calling a parameterized function from HTML?
If you add in another key/value pair to the hash in url_for
<%= url_for :action => :showProducts, :product => "toaster" %>
Your URL should go from, say, http://localhost:3000/showProducts to http://localhost:3000/showProducts?product=toaster
Here, we're adding parameters to the GET request. To access these parameters in the controller we use the params hash. For example to get the product (toaster):
params[:product] #=> "toaster"
I found the solution to my problem :
<a href="<%= url_for :action => :showProducts, :id=> 'Hello' %>">
.rb function:
def showProducts(param)
//Some code
end
I found the solution
def showProducts
#params['product']
end