I have some server side code set up to make a request to an external website and return a JSON object that is then passed to the client side of my node.js/express application. I then intend to perform some additional processing on the JSON on the client side.
In my index.js file I have the following code defined to render my view and make a RESTful call to the external website:
var express = require('express');
var router = express.Router();
var request = require('request');
// Urls for external server REST API function calls
var url = 'https://someserver.com/appserver/portal/api/1.0/results/recent';
/* GET list of recent reports */
router.get('/testapi', function(req, res, next) {
res.render('testapi', { title: 'List Recent Reports' });
});
/* TEST: function to GET report list */
router.get('/recentreports', function(req, res){
request({
url: url,
json: true
}, function (error, response, body) {
if (!error && response.statusCode === 200) {
res.send(body); // Send the response to the client
} else {
console.log(error);
}
})
});
module.exports = router;
Inside my jade view, I have a button set up to make a call to the /recentreports function and make a request (possibly AJAX request?) to receive the JSON object from the server.
My question is: how do I read the response from the server into my client side application so that I can process the JSON?
My jade view is as follows:
extends layout
head
block content
h1= title
p Welcome to #{title}
script.
// not sure what goes here
$(function()){
$('#getRecentReports').on('', function() {
$.get('recentreports', function(body) {
$('#jsonbody').html(body)
})
})
}
button(
onclick = "getRecentReports()"
)
Edit: updated .jade code after playing around with it a bit more
My recommended suggestion:
script.
$(function() {
$('#getRecentReports').on('click', function() {
$.get('recentreports', function(body) {
$('#jsonbody').html(body)
});
});
});
button(
id = "getRecentReports"
)
Renders this:
<script>
$(function() {
$('#getRecentReports').on('click', function() {
$.get('recentreports', function(body) {
$('#jsonbody').html(body)
});
});
});
</script>
<button id="getRecentReports"></button>
Or alternatively:
script.
function getRecentReports() {
$.get('recentreports', function(body) {
$('#jsonbody').html(body)
});
}
button(
onclick = "getRecentReports()"
)
Renders this:
<script>
function getRecentReports() {
$.get('recentreports', function(body) {
$('#jsonbody').html(body)
});
}
</script>
<button onclick="getRecentReports()"></button>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.