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

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!

Related

how can I make the DOM work with ejs and Mysql

I want to compare "test" with "angendaOficina".
test is a DOM element.
angendaOficina is a table in Mysql database.
When I run the code it tells me that test is not defined and I understand that it is because of the <%%> that I can, but if I remove it, it tells me that document is not defined.
<form name="formulario">
<div><input name="busqueda" placeholder="BUSCAR" required type="text" autofocus></div>
</form>
<div><button id="btn">BUSCAR</button></div>
<script>
function operation() {
var test = document.formulario.busqueda.value;
<% for (var i = 0; i < angendaOficina.length; i++){%>
<%if(angendaOficina[i].carpeta == test){
console.log("MATCH");
}else{
console.log("NO MATCH");
}
%>
<%}%>
}
var btn = document.getElementById("btn");
btn.addEventListener('click', operation, true);
I can't really do exactly what you wanna do, but i can at least help you to solve your problem.
You should not use EJS to import your database like this.
If you want to use your DB data like this, import it in the HTML JavaScript using GET requests.
To do requests you can either use a module like jQuery (which i don't recommend but it is surely the most known) or use the defaults XMLHttpRequest.
You can handle thoses requests in your express server like this :
expressApp.get("/getDatabase", (req, res) => { // "/getDatabase" is the url you wanna GET request.
res.json({
data: dbObject // "dbObject" is your DB data object.
})
})
Then, when you do a request to "/getDatabase" you will get a JSON object that contains data as your database data.

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>

How to display contents within a MySQL database through an html file?

Is it possible to open an html file, have it send some signal to a server-side application to query data from a mysql db and then return that data to that original html file? So instead of having some php or js program spit out an html file, can i create an 'index.html' file that when i click on, will display contents of my db? Thanks
If the question is limited to using only HTML, then this is not possible.
If you mean only using a static HTML page (allowing inline JavaScript), then there are lots of ways you could do what you want.
You could use client side JavaScript, served in a static page removing the need to run a backend like Node JS or some other kind of non static web server.
Something like this for your static HTML file:
<html>
<head>
<title>Using Fetch</title>
</head>
<body>
<script>
// Fetch your information here using client side JavaScript
// Do something
</script>
</body>
</html>
Your server side application can expose an endpoint that outputs some JSON, we will use the endpoint https://example.com/api/ and fetch it using Fetch API:
let url = 'https://example.com/api/';
fetch(url)
.then(res => res.json())
.then((data) => {
// Your data is in the variable 'data', do something with it
})
.catch(err => { throw err });
All together your HTML file could look something like this:
<html>
<head>
<title>Using Fetch</title>
</head>
<body>
<p id="data"></p>
<script>
let url = 'https://example.com/api/';
fetch(url)
.then(res => res.json())
.then((data) => {
document.getElementById("data").innerHTML = data;
})
.catch(err => { throw err });
</script>
</body>
</html>
That code is a basic example of getting some data from an endpoint and setting a paragraph on your page to show that information.

Node.js: How to exchange a JSON object [duplicate]

This question already has answers here:
How to access POST form fields in Express
(24 answers)
Closed 6 years ago.
My purpose is to send a JSON object from the client-side to the server. So taking into account the following details of the client:
<script>
var onClickFunct = function() {
trial1.send({
"test": $("#input_test").val(),
});
}
</script>
Where input_test is the name of my tag in the html page.
And where trial1 is implemented with the following code:
var trial1 = {
//notifica al server una nuova registrazione
send: function(data){
$.getJSON('/tst',data);
}
}
My Server can't see the object; infact if I print req.params it shows me "undefined".
app.get('/tst',function(req){
console.log(req.params);
});
My index.html reuire the following script <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
While the server require only express
Try changing:
app.get('/tst',function(req){
console.log(req.params);
});
to:
app.get('/tst',function(req){
console.log(req.query);
});
The req.params is for parameters in your routes, like:
app.get('/test/:name', function (req, res) {
console.log(req.params);
});
When you access /test/abc then the req.params.name will be "abc".
The $.getJSON() sends the data as query parameters, see:
http://api.jquery.com/jquery.getjson/
And for the query parameters you use res.query.
If it was a POST request and you wanted to access parameters passed in the request body then you would user req.body (but you would need to use a bodyParser middleware).
Remember to use GET only for reading operations, where in the query parameters you specify what you want to get or in what form, what order etc.
If you pass data to store in a database or something like that then use POST or PUT for that and pass the data in the request body (which can be JSON).
$ npm install --save body-parser
and then:
var bodyParser = require('body-parser')
app.use( bodyParser.json() ); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
your endpoint should look like this:
app.post('/tst',function(req){
console.log(req.body);
});
then use Jquery Post:
$.post('/tst',data);
body parser install example taken from here:
How to retrieve POST query parameters?
hope it helps :)

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

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