HTML page returns Undefined from API response - javascript

I've got the following JS which is attempting to return a value from an AWS API Gateway:
<script>
fetch("https://myapi/get")
.then(response => response.json())
.then(data => {
document.getElementById("website-counter").innerHTML = data.body
});
</script>
The API GW triggers a lambda function to get a value from a DynamoDB table.
Im attempting to display the retuned value by
<p>
CV Website Views: <span id="website-counter"></span><br/>
</p>
However, the "website-counter" returns an undefined value, not the required DB value.
Also, Ive set the CORS headers in the Lambda function itself. If i access the direct link to the API from AWS console, i get the retuned value from dynamodb as expected.

This post resolved the issue for me: ES6 fetch function returns undefined
This is now working fine:
<script type ="text/javascript">
function visitcount() {
return fetch("https://myapi/get").then(function(response) {
return response.json();
}).then(function(json) {
return json;
});
}
visitcount().then(function(result) {
document.getElementById("website-counter").innerHTML = result
console.log(result);
});
</script>

Related

Error initializing google maps API from backend node server to keep key secure

I built a webapp that follows the javascript tutorials for google maps api, and now I'm looking to secure the api key by moving whatever functionality is needed to a node server and passing the values of interest up to the front end. My server function is sending the api all the same arguments and is getting back what looks like a valid script string, which I'm passing to the front end and running eval(result) on. The issue is when I run eval() the Google maps API responds that I'm missing the arguments I've previously sent.
Am I going about this all wrong? Should I rebuild purely for nodejs? Thank you for any help.
JS function on the node server:
async function startmaps(){
var payload = {
key: process.env.GOOGLE_MAPS_API_KEY,
libraries: ['places', 'geometry'],
callback: 'initMap'
};
var data = new FormData();
data.append("json", JSON.stringify(payload));
var result = fetch('https://maps.googleapis.com/maps/api/js',
{
method: "POST",
body: data
}
)
.then((res) => res.text())
.then((dat) => {
return {
data: dat,
error: false,
errMsg: ''
};
})
.catch((err) => {
return {
data: '',
error: true,
errMsg: err.toString()
};
});
return result;
}
Calling function on the front end:
async function StartMaps(){
var result = await fetch('http://localhost:3000/mapinit')
.then((res) => res.json())
.then((data) => {
return data;
})
.catch((error) => {
return error;
});
if(result.data === "undefined" || result.error){
console.log("got error");
}else{
eval(result.data);
}
}
End result:API errors on eval of result.data
Tried sending Google the sensitive data to initialize the maps from the backend, and passing up to the front end JS the result, however what Google maps API returns seems to realize it's in another context and complains that it's missing the api key
"VM403:208 Loading the Google Maps JavaScript API without a callback is not supported: https://developers.google.com/maps/documentation/javascript/url-params#required_parameters
....
util.js:63 Google Maps JavaScript API warning: NoApiKeys https://develope..."
editing to note that if I run the resulting script from node js I get the error: 'ReferenceError: window is not defined'

jquery $.get success callback not working

I'm unable to access the result of my query despite checking in browser network(xhr) and seeing the data is returned successfully from api. But I can't even console.log the returned data. Not sure what's going on.
Here's my code:
// const url='/../../_public/api/news.php'; // does not work
const url='https://jsonplaceholder.typicode.com/users/3' // works
let getHandle = () => {
return new Promise(function (resolve){
$.get(url, {endpoint: 'titles', param: 'titles'}, (response) => {
console.log(response);
resolve(response);
})
})
}
getHandle().then((res) => {
console.log(res);
})
<script src="https://code.jquery.com/jquery-3.6.3.min.js"></script>
The problem is your api url, you need to start the local dev server with your PHP backend and change the url to something like '/api/news.php'
// I tested your code with the json placeholder API and it works

Using Lambda with NodeJS and fetching value correctly from Dynamo db, I cannot process the json data recieved

//Function to pull data from Dynamo DB (works)
async function pullone(sessionid) {
const params = {
TableName: dynamodbTableName,
Key: {
'sessionid': sessionid
}
};
return await dynamodb.get(params).promise().then((response) => {
return response.Item
}, (error) => {
console.error('Do your custom error handling here. I am just gonna log it: ', error);
});
}
//executing it
`exports.handler = async (event) => {
let sessionid = "45883754"
let data = pullone(sessionid)
return data
};`
//The above works well and the 'data' returned is
{ "school": "3wc", "sessionid": "45883754" }
I have tried to get values with data.school but itdoes not work. Is this an issue with Lambda because this is supposed to be a nobrainer. Your support will be appreciated. Thanks guys
I tried data.school or data.sessionid but the values were not coming forth
For future posts, please show the error message or what you recieved that was unexpected.
Im your case, the Lambda function is doing an asynchronous call to fetch the data meaning that the lambda itself is asynchronous. In your code that calls the Lambda, you meed to add await such that the call looks like this:
let data = await pullone(sessionid)
console.log(data.school)

how to use fetch in order to get and display information

i managed to use fetch to get some information about the world population. i got the information and displayed them on my page. the is the url of getting the population of Norway (https://d6wn6bmjj722w.population.io/1.0/population/Norway/today-and-tomorrow/) and this is the list of all countries (https://d6wn6bmjj722w.population.io/1.0/countries). i'd like to know how can i send a different request (choose another country). in my code code, there's a textbox that gets a country name from the user. i want the same name to be used as request.
here's my code for fetching the information.
function fetchcountryList(){
fetch("https://d6wn6bmjj722w.population.io/1.0/countries").then(response=>{
if(!response.ok){
throw Error("ERROR")
}
return response.json();
}).then(data=>{
console.log(data.countries);
const cl=data.countries.map(user2=>{
return `<p>Country List:${user2}})</p>`
}).join()
document.querySelector("#myFetch2").innerHTML=cl;
})
.catch(error=>{
console.log(error)
})
}
function fetchCountry(){
fetch("https://d6wn6bmjj722w.population.io/1.0/population/Norway/today-and-tomorrow/")
.then(Response=> {
if(!Response.ok){
throw Error('ERROR')
}
return Response.json();
}).then(data=>{
console.log(data.total_population);
const html=data.total_population.map(user=>{
return `<p>Population: ${user.population}</p>`
}).join()
document.querySelector("#myFetch").innerHTML=html;
})
.catch(error =>{
})
}
well i don't think your second function is working, if yes then replace console.log to document.write, as you need to work with object.
in your main function where you are appending list items, pass a variable x,
like this:
const x = data.total_population.x;
list.appentchild(document.createTextNode(x));

ReactJS get token string from API fetch

I set up an API in Java. But now I'm developping a client in ReactJS. The authentication uses a JWT Token. With Postman, when I send a POST request to the authentication URL, it returns me a JWT token like this :
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZHVzZXIiOjEsImlzcyI6ImF1dGgwIn0.0BXAQl-yMIDeAU6Emppo6LBIm1RAdLa9vDWbQkdLs1o
That's exactly what I want. But I don't know how to retrieve a string after a fetch call in ReactJS.
I tried to use the promises and wrote this :
.then((data) => {
data.text().then((token) => {
alert(token)
})
})
But it returns me nothing, I have an alert with no text.
How to get String from the Object Response returned by the fetch ?
Maybe you back end server return Content-Type=application/json? Instead text() method try using json().
Try this:
fetch('/next/page')
.then(function(response) {
return response.text();
})
.then(function(text) {
// <!DOCTYPE ....
console.log(text);
});
I was facing the same issue and was able to get the token with this:
.then(res => res.json()).then(res => {
let token = res.token;
console.log("token: ", token);
});
Source:
https://developer.mozilla.org/en-US/docs/Web/API/Body
The text() method on that response object is what you are looking for.
Using await syntax I think is a bit simpler than using then() With await, this in this.setState() is scoped as expected.
async getStrResponse() {
const response = await fetch('myController/GetStringTest');
const stringResponse = await response.text();
this.setState({ someStr: stringResponse, loading: false });
}

Categories

Resources