I want a simple example of how to send data from a nodeJS server as JSON to Flash, then Flash decodes the JSON. This is part of what I want:
Server
json = {name : "Person", id: "1"}
Flash
myinput.text = json.id + ":" + json.name
Use AMF.js, which is the subject of a related question which discusses the syntax and debugging process.
On server-side:
app.post('/login', (req, res) => {
//Some code with error here...
errorModel = {
code: 400,
message: 'Wrong username or password'
}
req.flash('error', JSON.stringify(errorModel))
res.redirect('/login')
})
On client-side (for example using EJS view):
<% if (messages.error) { %>
<p>
<%= JSON.parse(messages.error).message %>
</p>
<% } %>
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 am setting this up as stated in the docs for replacing values within files:
prompting() {
return this.prompt([{
type : 'input',
name : 'name',
message : 'Your project name',
default : this.appname // Default to current folder name
}, {
type : 'input',
name : 'chaincodeTitle',
message : 'Chaincode folder name'
}]).then((answers) => {
this.log('app name', answers.name);
this.props = answers;
});
}
// Creates all the files and directories from a hyperledger project template source
writing() {
this.fs.copyTpl(
this.templatePath('sdm/artifacts/local/config.json'),
this.destinationPath('./' + this.props.name + 'hyperledger/local' + '/config.json'),
{props: this.props.name}
);
}
Here's where I put the tag in my JSON file:
{
"host": "localhost",
"port": "3000",
"logLevel": "INFO",
"channelCfgTxn": "../../../artifacts/local/channel/mychannel.tx",
"chaincodeId": "MikeGcc",
"CC_SRC_PATH": "../../../app/chaincode",
"chaincodePath": "<%= props %>",
"chaincodeVersion": "v0",
"queryFunction": "getVersion",
"keyValueStore": "/sim/fabric-client-kvs-local",
"chaincodeName": "<%= props %>",
"jwt_expiretime": "360000",
"client": "http://localhost:4200/",
"registerSupplierRoute": "register-supplier/"
}
But when I run my yeoman generator, yeoman doesnt detect its own tag it seems like and is outputting the string: <%= props %>
So I get the following error when it finishes:
info: [packager/Golang.js]: packaging GOLANG from <%= props %>
events.js:183
throw er; // Unhandled 'error' event
^
Error: ENOENT: no such file or directory, lstat '/home/mike/mikehyperledger/app/chaincode/src/<%= props %>'
This has been killing me for two days now. Anyone familiar with Yeoman who might know whats happening here?
The problem was that this command was in the writing block which is a promise to write and all the commands in that block happen asynchronously.
To fix this problem, I had to create a block outside of writing called "end()" and insert my fsCopyTpl in there like this:
end() {
this.fs.copyTpl(
this.templatePath('sdm/artifacts/local/config.json'),
this.destinationPath('./' + this.props.name + 'hyperledger/local' + '/config.json'),
{props: this.props.name}
);
}
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);
});