how to send json data to html page in node.js - html

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);
});

Related

How do I send data from express => html

So say I have some form data in express right, and I'm checking it against a db. Say it doesn't find the db, so I have an if then statement for that. How would I edit a p element in a separate html file to say 'Account not found!' upon this if statement being activated? My code would be something like this..
let userData = keyv.get(username)
if (!userData) {
console.log('couldn't find user')
//edit p element with id status
}
else {
...
}
Thanks.
You need to use a templating engine and pass the userData variable when rendering the view.
You can do something like
app.get('/:id', function(req, res) {
// try to get user data
res.render('pages/index', {userData});
});
userData will be accessible from the view. I recommend you use EJS for this, although there are other engines like Pug, Handlebars, etc
EDIT:
I misunderstood your question, but the answer is the same except you render different data. If the user isn't found then you can render an error message instead.
app.get('/:id', function(req, res) {
// try to get user data. do the following if the user isn't found
res.render('pages/index', {
error: 'User not found'
});
});

cannot able to pass data from express to ejs?

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>

Pretty print the JSON returned by express in Node.JS

I'm trying to follow this great design recommendation documentation for my server development in Node.JS regarding the JSON pretty formatting when returning it to the caller.
I can't figure out to do so when returning a file though:
app.get('/data.txt', function(req, res){
return res.sendFile(path.resolve(__dirname + '/views/myData.json'));
});
Would you have any suggestion?
You can simply require the JSON file using :
let fileContents = require(path.resolve(__dirname + '/views/myData.json'));
And then
app.get('/data.txt', function(req, res){
return res.send(fileContents);
});
Note: This approach doesn't send the file.It sends the contents of the JSON file in response.

Creating a non-REST JSON API server with node

I am relatively new to NodeJS, but I'm porting an existing API server written in PHP to use NodeJS. I started out looking at Express, but realised that with all the layout-rendering and templating stuff in Express, it wasn't suited for the task. Then I looked at Restify, but realised it's REST-ness wouldn't work with the model of this API.
I don't want anything that is tied to a database, or any specific way of setting out the API endpoints. Is the best solution to fully roll my own server, without the help of any libraries?
EDIT: Sorry, it seems I was unclear. I am trying to recreate the PHP API as close as possible, and the PHP version does not use REST. It has a few different PHP scripts which take some POST parameters.
If you just want a simple JSON API, Express is still an option. Layouts, temptating and middleware are optional, and you can just use simpler functions.
var express = require('express');
var app = express();
app.use(express.bodyParser());
app.post('/', function(req, res) {
// req.body is an object with POST parameters
// respond with JSON
res.json(200, { data: 'payload' })
// or show an error
res.json(500, { error: 'message' });
});
app.listen(80);
That is one of the simplest solutions available. Unless you want to do request body parsing, checking the HTTP request method, other things yourself, then you can create your own server. That would look more like this:
var http = require('http');
http.createServer(function(request, response) {
if (request.method === 'POST') {
var data = '';
request.on('data', function(chunk) {
data += chunk;
});
request.on('end', function() {
// parse the data
});
}
}).listen(80);
A method like so would also require checking the path as well as other things that would be handled automatically in Express.

Can you include JSON-like data in initial response using connect/express?

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!