Getting data from AWS Dynamodb through API Gateway using NodeJS Error - amazon-web-services

I'm learning to build a API using Amazon Web Services' API Gateway, DynamoDB, and Lambda.
I've been following a video playlist tutorial on Youtube. So far, I've created the desired Lambda Function, DynamoDB Table, and also the API Gateway.
Now all I need to do is build a frontend that display my current items in the table and also the entry.
So far I made it to this part here.
In the video, he uses JavaScript to make an ajax request and fetch the items in the DynamoDB Table. I've written the same ajax request with the html.
<html>
<head>
<h1 style="color:rosybrown;">Latest guestbook entries:</h1>
</head>
<body>
<div id="entries">
</div>
<h1>New Entry</h1>
<form>
<label for="msg">Message</label>
<textarea id="msg"></textarea>
<button id="submitButton">Submit</button>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
var API_URL = "someURL/prod/entries";
$(document).ready(function(){
$.ajax({
type: "GET",
url: API_URL,
success: function(data){
$("#entries").html("");
data.Items.forEach(function(guestbookItem){
$("#entries").append("<p>"+guestbookItem+"</p>");
})
}
});
});
</script>
</body>
So here I'm going to explain my purpose. The goal is the display the items in the DynamODB table that I have created while also accepting new entries. It has a date and message item.
The API Gateway has an /entries resource and has two methods, GET and POST. /prod means it was deployed on a production stage.
When invoking the URL for the GET method. I receive this output
"{\"Items\": [{\"date\": 20180512, \"message\": \"this is my 4th message\"}, {\"date\": 20180513, \"message\": \"I love AWS\"}], \"Count\": 2, \"ScannedCount\": 2, \"ResponseMetadata\": {\"RequestId\": \"SOME_REQUEST_ID\", \"HTTPStatusCode\": 200, \"HTTPHeaders\": {\"server\": \"Server\", \"date\": \"Mon, 14 May 2018 20:32:43 GMT\", \"content-type\": \"application/x-amz-json-1.0\", \"content-length\": \"160\", \"connection\": \"keep-alive\", \"x-amzn-requestid\": \"SOME_REQUEST_ID\", \"x-amz-crc32\": \"2401247050\"}, \"RetryAttempts\": 0}}"
However, after running the index.html file on my local host.
The entries did not appear. When I checked the console, it turns out I receive the following error
index.html:33 Uncaught TypeError: Cannot read property 'forEach' of undefined
at Object.success (index.html:33)
at u (jquery.min.js:2)
at Object.fireWith [as resolveWith] (jquery.min.js:2)
at k (jquery.min.js:2)
at XMLHttpRequest.<anonymous> (jquery.min.js:2)
I was not really sure what is going on. Items does exist in the response. I've been stuck with this for days. If anybody could point out what I was missing, it would be greatly appreciated!

Related

Django - Google Analytics not tracking properly

Followed a tutorial and added google analytics to my django site by placeing the tracking code into the head of my base.html as well as a different page that does not extend from base.
<!DOCTYPE html>
<head>
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-trackcode"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-trackcode');
</script>
</head>
However the other day I ran a facebook ad and sent over 200 clicks to my site, google only tracked 30 of these clicks. And when viewing my pages it does not seem to properly track individual pages and only tracked 3 pages, the majority of the traffic is just under the root domain.
(its a blog style site so i need to see exactly what pages users are most interested in)

How do I inject a template into another template in Flask [duplicate]

I Want to develop a flask navigation bar like Google Contacts.
I Want to Render a particular HTML page inside the red box (as in the picture) when I click each of the navigation buttons (the green box as in picture) without refreshing the page.
I have already tried using
{% extends "layout.html" %}
As #Klaus D. mentioned in the comments section, what you want to achieve can be done using Javascript only. Maybe your question were
How can I send a request to my server-side (to get or fetch some information) and receive back a response on the client-side without having to refresh the page unlike the POST method usually does?
I will try to address the aforementioned question because that's probably your case.
A potential solution
Use Ajax for this. Build a function that sends a payload with certain information to the server and once you receive back the response you use that data to dynamically modify the part of the web-page you desire to modify.
Let's first build the right context for the problem. Let's assume you want to filter some projects by their category and you let the user decide. That's the idea of AJAX, the user can send and retrieve data from a server asynchronously.
HTML (div to be modified)
<div class="row" id="construction-projects"></div>
Javascript (Client-side)
$.post('/search_pill', {
category: category, // <---- This is the info payload you send to the server.
}).done(function(data){ // <!--- This is a callback that is being called after the server finished with the request.
// Here you dynamically change parts of your content, in this case we modify the construction-projects container.
$('#construction-projects').html(data.result.map(item => `
<div class="col-md-4">
<div class="card card-plain card-blog">
<div class="card-body">
<h6 class="card-category text-info">${category}</h6>
<h4 class="card-title">
${item.title_intro.substring(0, 40)}...
</h4>
<p class="card-description">
${item.description_intro.substring(0, 80)}... <br>
Read More
</p>
</div>
</div>
</div>
`))
}).fail(function(){
console.log('error') // <!---- This is the callback being called if there are Internal Server problems.
});
}
Build a function that will fetch the current page via ajax, but not the whole page, just the div in question from the server. The data will then (again via jQuery) be put inside the same div in question and replace old content with new one.
Flask (Server-side)
''' Ajax path for filtering between project Categories. '''
#bp.route('/search_pill', methods=['POST'])
def search_pill():
category = request.form['category']
current_page = int(request.form['current_page'])
## Search in your database and send back the serialized object.
return jsonify(result = [p.serialize() for p in project_list])
Thank you #CaffeinatedCod3r,#Klaus D and #newbie99 for your answers.
I Figured it out. instead of using Flask we can use Angular JS Routing for navigation.
Here is the example that i referred:
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular-route.js"></script>
<head>
<base href="/">
</head>
<body ng-app="myApp">
<p>Main</p>
Banana
Tomato
<p>Click on the links to change the content.</p>
<p>Use the "otherwise" method to define what to display when none of the links are clicked.</p>
<div ng-view></div>
<script>
var app = angular.module("myApp", ["ngRoute"]);
app.config(function($routeProvider, $locationProvider) {
$routeProvider
.when("/banana", {
template : "<h1>Banana</h1><p>Bananas contain around 75% water.</p>"
})
.when("/tomato", {
template : "<h1>Tomato</h1><p>Tomatoes contain around 95% water.</p>"
})
.otherwise({
template : "<h1>Nothing</h1><p>Nothing has been selected</p>"
});
$locationProvider.html5Mode(true);
});
</script>
</body>
</html>
By Using $locationProvider.html5Mode(true) i was able to remove the # from the URL.

Rendering Grafana inside django website using API Key

I’m attempting to pass an API token for a user to grafana from our own internal website so that the main gui renders in an iframe. We don’t want the users to have to log into grafana after they have logged into our site, so we are creating their users in grafana, building an API token and attaching that to the user for our website. When the user goes to the page that has the grafana iframe, we are sending an ajax get request with the token so grafana renders the main dashboards with the users information.
If we do just a standard iframe everything works fine and we render inside the frame. We can get to the login page and do everything we need to. When I add the token so we don’t need to authenticate nothing renders and I see no errors/logs on either grafana or the website. If I send an invalid token I see the expected “401 invalid Api key” error on both the website and the grafana logs. This is what I’m sending from the website…
<div class="content">
<div class="container-fluid" id="container">
</div>
</div>
<script>
$.ajax({
url: "{{url}}",
type: "GET",
beforeSend: function(xhr){
xhr.setRequestHeader('Accept', 'application/json');
xhr.setRequestHeader('Authorization', 'Bearer {{token}}');
},
success: function(r) {
$('#container').html(r);
}
});
</script>
With the above nothing happens, I get no errors or logs. If I keep everything else the same and just adjust the token to make it invalid, grafana says it is invalid, so I know it is making it to the server. Why is nothing coming back to be rendered?
Thanks!
That' s an Error in Grafana-API, the generated API-Key. Use a Key that is generated inside Grafana

Access denied when embedding quicksight URL

I am trying to embed an AWS Quicksight dashboard into our application but I am having some trouble with the embed process. The URL has been generated correctly and but I get a permission denied error when I attempt to embed it.
I am able to load the generated URL directly in a new tab but when I attempt to embed it I get a 401 error.
I have whitelisted the domain in the Quicksight console and am accessing the page over HTTPS. The complete test page is shown below.
The following code is what I am using to test embedding. It was taken from an Amazon example.
<!DOCTYPE html>
<html>
<head>
<title>My Dashboard</title>
<script src="https://unpkg.com/amazon-quicksight-embedding-sdk/dist/quicksight-embedding-js-sdk.min.js" ></script>
<script type="text/javascript">
function embedDashboard() {
var containerDiv = document.getElementById("dashboardContainer");
var params = {
url: "<link that works in a standalone browser tab>",
container: containerDiv,
parameters: {
},
height: "700px",
width: "1000px"
};
var dashboard = QuickSightEmbedding.embedDashboard(params);
dashboard.on('error', function(err) {console.log('dashboard error:', err)});
dashboard.on('load', function() {});
}
</script>
</head>
<body onload="embedDashboard()">
<div id="dashboardContainer"></div>
</body>
</html>
Amazon sends a 302, followed by a 401. Which results in a frame with the error message "We can't display this page (Not Authorized).
The first request in the image fetches a fresh link from the server and the subsequent two are the framing attempt.
I would expect that if something was wrong with my authorization then a loading the link in it's own tab would not work. I think the issue must be with the frame but don't know what other options to check beyond the whitelist.
Does anyone have any idea what else I can try?

customize the yammer feeds

I am getting the yammer feeds on my page using the following code in content editor webpart.
<div id="embedded">
</div>
<script src="https://assets.yammer.com/assets/platform_embed.js"></script>
<script> yam.connect.embedFeed({
container: "#embedded",
network: network,
feedType: "group",
feedId: "all",
config: {
header: false ,
footer: false,
}
});
</script>
Is there a way to iterate through each of the feeds and customize on how it appears?
I'm facing the same issue. The embedded feed is contained in an iframe, which is under the yammer.com domain. It would be very challenging to access those dom elements from your app's domain, due to the same origin policy, let alone to modify them. You may find hacks or work-arounds but they are not trivial tasks to achieve.