fetching the data dynamically from RestEnd points - javascript

I need to get the data from the REST endpoint and display it in some sort of filterable table, and update it if anything changes in the server.
(I dont want to get the data from static JSON file but everytime i make a GET call to rest end point i will get the data which is in json format)
are there any tutorials which can help me with this?

To make a fetch call to an API endpoint, you would use JavaScripts built in fetch method. See below, I've built a fetch and even put in a dummy endpoint that returns actual JSON so you can see that it's working. Just replace the URL right after fetch with the the API endpoint you want to get JSON from...
fetch('https://jsonplaceholder.typicode.com/users')
.then((response) => {
return response.json()
})
.then((data) => {
console.log(data)
})
.catch((err) => {
console.log(err)
})
The first .then makes sure the data is turned back into JSON and then passes the data down to the second .then. Inside that second .then is where you would handle the response by using (in this case) 'data' as the variable name. You can set those parameters to whatever you want to call them though. Finally, the .catch simply console logs the error message if the fetch is unsuccessful.
Here is a repl so you can see it working. Just hit run and you'll see the response: https://repl.it/repls/UnfoldedVibrantProcessor

You'll need to continuously call the API endpoint to check for the data, updating the local dataset with each response. If the API is self-developed,restful and used solely for this example, then the data will be cached so it won't have a massive impact on performance/resources (if the data isn't changing rapidly).
Just shove the code you're using to call the endpoint e.g. Ajax calls within a setInterval() loop and it should work fine, updating the UI (table & contents) as you're re-performing the process over and over.
setInterval(function(){
some AJAX call getting data ...
... use the AJAX response (data) to re-draw/update the table contents
}, 3000);
The process for getting what you want:
Implement continuous API caller (setInterval); initiated on document load.
Learn and Implement external API request e.g. AJAX
Parse data, create HTML using data to create a table structure or use external table library.
Use created HTML to dynamically modify the DOM using document.getElementById("#table you made in your html").innerHTML = ^#3

Related

Force synchronous query from PostGreSQL with NodeJS (and then return it to a function that parses that)

I have a database that holds a table of a list of users (and their respective usernames and passwords). I have a login system that runs a function that returns false when the user is not found and the username/password when it is found. That is then used in the login system but that's irrelevant.
My problem is that that function has to send a query to the database. But the callback actually can't return anything and so I can't just use
await database.query('query things', data = await function(err, res) {function things});
I tried declaring a variable and then inside the query callback setting that variable to the fetched data, and then outside of that query the await holds the rest of the code back, but it just returns undefined. The await does not do anything because of the multiple promise resolves (I think). So what ends up happening is the function returns undefined and the server crashes.
Is there a way that I can pass the fetched data through the function and back to the login system?
Structure:
login calls fetch function; fetch function queries database; callback sets a passthrough; fetch function receives that passthrough and parses it and returns things to the login.
Thank you for being helpful, internet. Unlike last time.
It turns out that because there is a callback inside it does not return a promise so async/await is not useable. I still wanted to not have the server instantly crash when an error occurred but try/catch works fine.

How do I intercept an API call and display data from it using a UserScript?

There's a webapp that makes a request (let's call it /api/item). This request returns a json body with a field called itemData which is normally hidden from the user, but I want to make that shown.
So how do I make a userscript that listens for the request at /api/item and displays the itemData field?
For reference the way the webapp is making the request is:
return Promise.resolve(new Request(e,r)).then(sendCookies).then(addLangParam).then(addCacheParam).then(addXsrfKey).then(checkZeroRating).then(function(e) {
return fetch(e)
}).then(checkStatus).then(checkApiVersionMismatch).then(checkApiResponse)
Most of that is irrelevant, but the important part is Request (I think).
This webapp is not using XMLHttpRequest, but the Fetch API.
You can use the fetch-intercept npm module to intercept fetch requests. Example code:
import fetchIntercept from 'fetch-intercept'
fetchIntercept.register({
response(response) {
console.log(response)
return response
}
})
Do you have access to the promise returned ?
If so, then you may add another "then".
Otherwise, you may overwrite "checkApiResponse"

node.js and hapi: fetching data from a database synchronously

Coming from a .net world where synchronicity is a given I can query my data from a back end source such as a database, lucene, or even another API, I'm having a trouble finding a good sample of this for node.js where async is the norm.
The issue I'm having is that a client is making an API call to my hapi server, and from there I need to take in the parameters and form an Elasticsearch query to call, using the request library, and then wait for the instance to return before populating my view and sending it back to the client, problem being is that the request library uses a callback once the data is returned, and the empty view has long been returned to the client by then.
Attempting to place the return within the call back doesn't work since the EOF for the javascript was already hit and null returned in it's place, what is the best way to retrieve data within a service call?
EX:
var request = require('request');
var options = {
url: 'localhost:9200',
path: {params},
body: {
{params}
}
}
request.get(options, function(error, response){
// do data manipulation and set view data
}
// generate the view and return the view to be sent back to client
Wrap request call in your hapi handler by nesting callbacks so that the async tasks execute in the correct logic order. Pseudo hapi handler code is as following
function (request, reply) {
Elasticsearch.query((err, results) => {
if (err) {
return reply('Error occurred getting info from Elasticsearch')
}
//data is available for view
});
}
As I said earlier in your last question, use hapi's pre handlers to help you do async tasks before replying to your client. See docs here for more info. Also use wreck instead of request it is more robust and simpler to use

res.send and res.render calls

I am trying to determine if i can call res.send(data) and then res.render('reports') simultaneously.
To explain further in detail, when i route to '/reports', first on my server side i making a REST call to an API which returns back json data. Now i want this json data to be accessed on the client, for which i am making an ajax call from my javascript. Hence the use of res.send(), but i also want to render the page in this call
So it looks like the following on my server side code
router.get('/reports', function(req,res){
//Making the REST Call to get the json data
//then
res.send(json);
res.render('reports');
});
Every time i hit the '/reports' on the browser, I see the json value instead of the page being rendered and my console throws an Error: Can't set headers after they are sent.
You could use content negotiation for that, where your AJAX request sets the Accept header to tell your Express server to return JSON instead of HTML:
router.get('/reports', function(req,res) {
...
if (req.accepts('json')) {
return res.send(theData);
} else {
return res.render('reports', ...);
};
});
Alternatively, you can check if the request was made with an AJAX call using req.xhr (although that's not 100% failsafe).
No you can't do both, but you could render the page and send the data at the same time:
res.render('reports',{data:json});
and then access those data in the newly rendered page.
alternatively you could send a flag when making the call , and then decide whether you want to render or send based on this flag.
Ideally, it needs to be 2 separate route, one spitting json and other rendering a view. Else, you could pass a url param, depending on which you return json or render a view.
router.get('/reports/json', function(req,res){
var data = JSON_OBJECT;
res.send(data);
});
router.get('/reports', function(req,res){
var data = JSON_OBJECT;
res.render('path-to-view-file', data);
});
No, you can't. You can only have a single response to a given request. The browser is either expecting an HTML document or it is expecting JSON, it doesn't make sense to give it both at once.
render just renders a view and then calls send.
You could write your view to output an HTML document with a <script> element containing your JSON in the form of a JavaScript literal.

AngularJS $http.put PUT Method not sending Data

I'm switching from jquery $.ajax, which was working fine, to using AngularJS $http.put to access a restful API.
I can make an API call, but the PUT data isn't getting sent - so my API sees a PUT request with an empty data object, which should contain a JSON string -> data.values = 'a json structure'
$http.put(
$rootScope.api_url,
{
values: jsonifiedValues
},
{
headers: {
apihash: sha256hash
}
}).success(function(data,status,headers,config){
// handle success
}).error(function(data,status,headers,config) {
// handle failure
});
I've not used AngularJS's $http before, but when I dump out the data in my PHP api it's just empty. this is how I'm pulling it from the request in the PHP:
parse_str(file_get_contents('php://input'), $put_vars);
$arr_req_data = $put_vars['values'];
In my API if the apihash sent from the request doesn't match the sha256 hash built on the PUT values, it fails.
This is working in JQuery, just failing now I've switched to $http. I'm not sure why the PUT data seems to be empty.
The return value from file_get_contents('php://input') will be a JSON string (provided everything got sent), so parse_str is not the right function to handle that data.
Instead use json_decode.
Also there is no need to send jsonified values, it will just make things more complicated as you'll have to use json_decode twice.

Categories