Get data from Node.js via Express - javascript

I have a server with Node.js and I use Express to build a web app.
My server is already able to get an array from a database using a function (rss_interrogDB). Now I want to use this array to display a list in the html page. But I must be missing something...
On the server-side my code is:
app.get('/', function(req, res) {
rss_interrogDB(function() {
// don't konw what to add here
});
On the html page the code is:
$.get('/', {}, function(data){
// not sure it is the right code
console.log(data);
// then the code to create a list from the array (no pb with that)
});
Thank you for your help!

Assuming your DB gives you an array of data, add something like this to your server code:
app.get('/', function(req, res) {
rss_interrogDB(function(serverData) {
res.send(serverData);
});
});
You could manipulate the serverData object and build one that is more suitable for the client before you send it back, but that depends on what you want to do.

Related

In an express application ,how can the javascript file in public folder access the database API written in routes folder under index.js

Aim of the project is,accessing the mysql database at localhost/phpmyadmin on clicking a button from the client side and getting the data from the database for filling up a table on client side.
This project is done using an express application.
Code for database interface written under routes folder, index.js file:
var express = require('express');
var router = express.Router();
var mysql = require('mysql');
var connection = mysql.createConnection({
'host':'localhost',
'user':'root',
'password':'',
'database':'displayu'
});
connection.connect();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index');
});
router.get('/getusers',function(req,res,next){
var x;
connection.query('SELECT * FROM sample', function(err,result,field){
if (err){
throw error;
}
else{
x = res.json(result);
console.log(x);
}
});
});
module.exports = router;
On localhost:3000 the client side code written in views folder under index.html and the javascript logic under public folder results in a button and an empty table.I want to make use of the code written under server side routes folder onclick of this button to access the database and fill this data into the table.
I don't know the exact steps to do this requirement. I have the client side code and the server side code but need help to link them both to get output.
As already suggested you can achieve that by doing an AJAX request from your client side js.
You could do this with native JavaScript by using the XMLHttpRequest utilities.
For example:
function populateTable() {
// Handle your data here..
}
var GetUsersData = new XMLHttpRequest();
GetUsersData.addEventListener("load", reqListener);
GetUsersData.open("GET", "/getusers");
GetUsersData.send();
You could also use jQuery, depending on your project. If you already use it, I'd recommend using the included jQuery.get() function, which is quite a bit simpler than using native JS.
If you are not using jQuery in your project at the moment, you should stick to doing it the JS native way, also depending on how many AJAX requests you want to make and also keeping in mind how many you have to manage/debug going forward.
Both of these ways are very interesting and I'd suggest reading up on at least one of them, as they are very useful and you will at some point have to use AJAX again.

How to fetch the data from in memory of Express?

Hello I am trying to mock the API using swagger and express, in which I require data stored from the in memory database.
Following is my code, by which I am not able to get the data and it gives me syntax error.
I am using petstore application for mock.
Following is the script I modified as per my need.
What is wrong with the script.?
app.get('/pets', function(req, res, next) {
var myDB = new MemoryDataStore();
myDB.get('/pets',function(err, res){
});
});

How do I iterate over a JSON array using Jade and Node.js

So I have this JSON array apiData being passed on to the view as data.
Backend
router.get('/', function(req, res) {
var data = JSON.stringify(apiData);
res.render('gallery', { data: apiData });
});
Frontend
extends layout
block content
h1 MyProject
!{JSON.stringify(data)}
I am trying to cache !{JSON.stringify(data)} in a variable and iterate through it in the jade file. I am completely new to jade. How could I go about doing this?
You have a few problems in your code, like not using the stringification you do server side at all.
But you don't even need JSON here. Simply pass the array and iterate on it :
Backend
router.get('/', function(req, res) {
res.render('gallery', { data: apiData });
});
Frontend
extends layout
block content
h1 MyProject
each thing in data
p= thing
You'll find examples of iteration in the documentation

Specific url and parameter in Node.js project

I have 2 qeustions :
1. I want my project's url to be like 127.0.0.1:8080/param=id and I couldnt do it, I tried:
app.get('/param=id', function(req, res) {
console.log(req.param("id"));
});
if I write '/param/:id' it works but I dont want the url to look like this
I want my program to send message according to the id a json message or string to the client
So my second question is how the client gets the response - I want the message to go throgh a script in the client's side?
I would suggest using req.query instead of req.params:
app.get('/', function(req, res) {
console.log(req.query.id);
// or you may still use req.param("id")
});
requesting it like
HTTP GET 127.0.0.1:8080/?id=my_id
query is a different way of sending data to the server, designed to send key-value pairs.
Though, if id is the only thing you want to send to the server, I would recommend to stick with params, e.g.:
app.get('/:id', function(req, res) {
console.log(req.params.id);
});
requesting it like
HTTP GET 127.0.0.1:8080/my_id

Express middleware not having an effect

I have the following code:
var express = require('express');
var app = express();
app.use(express.bodyParser());
app.use(express.cookieParser());
var port = Number(process.env.PORT || 5000);
app.get('/test/:id', function(req, res) {
res.send(req.params);
});
app.listen(port);
console.log("Listening on port " + port);
When I hit http://localhost:5000/test/12345 in my browser, I see:
[]
But I'm expecting to see the populated req.params object with id: 12345. Any idea what I'm doing wrong?
Thanks.
Checked and saw that req.params is actually an associative array, which is almost similar to object but not quite. Not sure why express defined it as such. The only benefit it gets is the added length property for an array. And res.send will try to JSON.stringify your output, which in turn will see that it's an array and only take care of indexes which are numeric. Hence the empty [] as return value.
You can validate this by doing -
var myParams = {};
Object.keys(req.params).forEach(function(key){
myParams[key] = req.params[key];
});
res.send(myParams);
You can also see that JSON.stringify only cares about numeric index by defining your route as such -
app.get('/test/:0', function(req, res) {
res.send(req.params);
});
The response object will be named after your id. If you check it in your browser's traffic you can see a file called 12345. Though you can check that your server gets the id by logging it on the server side.
app.get('/test/:id', function(req, res) {
console.log(req.params);
res.send(req.params);
});
If you want to pass variables to a view you might want to use the res.render(...) function where you can pass in arguments.
To get the 123451 send the res.send(req.params.id);.
The reason why you are not getting anything using res.send(req.params) is because req.params is an instance of Array and default mechanism tries to covet an array into string which is giving you [].
What you could do to see all params is as follows:
app.get('/test/:id', function(req, res) {
res.send(require('util').inspect(req.params));
});
That will give you output like (using this URL http://localhost:5000/test/12345):
[ id: '12345' ]
That approach will also work with routes having more parameters e.g. the following code snippet and that request http://localhost:5000/test/name/234
app.get('/test/:name/:id', function(req, res) {
res.send(require('util').inspect(req.params));
});
will give you:
[ name: 'name', id: '234' ]
Alternatively, if you would like to get JSON formatted output of a JavaScript object, you can use res.json. But note that json will also generate [] if you perform res.json(req.params) as it will render req.params array in a standard way.
I hope that will help.
Note that as of 9th April 2014 (Express version 4.0.0) req.params is an object instead of an array so you should not have similar issues with v4.0.0 and your code should work as expected.
app.get('/test/:id', function(req, res) {
res.send(req.params);
});
The problem isn't your middleware. Neither bodyParser nor cookieParser provide the named url parameter parsing. That being said, your code looks correct to me. Are you absolutely certain you restarted your node server after making the code change?

Categories

Resources