How do I fetch a base64 string via an API call - javascript

The Fetch API will not run when I try to get a base64 string. What am I missing?
I've tried using a standard fetch in javascript, which is fine on all other calls until it's base64. It doesn't even reach the alert.
fetch(vimgurlone)
.then(response => response.json())
.then(dataimage1 => {
alert("here");
document.getElementById("theactualdata").innerHTML = dataimage1.Content;
})
.catch(error => console.error(error))
The json response will be something like:
{ Content: "brtergbrtbrtbwrtnhtehrth4t5h......" }
I would like receive and then assign the data to a variable and then display it or at least get to the alert message in the code above. The variable/URL "vimgurlone" is valid and displays a json response when pasted into a browser, but the fetch will not run. Do I need to decode it or something? The base64 string can be quite long. Thanks.

Ignore me! the issue was the API hadn't enabled cross origin requests, the code above is fine.
Thanks for the suggestions.

Related

display the data json responses using javascript or in console

I have a page that has much data I want to use. I inspected the page with Google Chrome to find the URL of the data (Network XHR). I get the request URL and when I open it, it does not show me anything, but in the preview and in the responses I can see the data. I tested some JavaScript codes to get JSON data from this URL, but it always errors.
I tested some command in console to display the text responses in console but nothing please I need your help to get this data using JavaScript
some codes I tested:
fetch( 'https://xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx?&action=get_vehicles' )
.then( response => response.text() )
.then( response => {
.then(function(data) {
console.log(data.data);
} );
`
headers
headers
responses
preview
You can get the fetch api call by going in the network tab in Chrome Developer Tools, clicking with right button in the request and then clicking in copy > copy as fetch like so:
fetch("https://xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx?&action=get_vehicles")
.then((response) => response.json())
.then((data) => console.log(data))
.catch((err) => console.log(err));

Fetching local JSON object with React.js problem, Error: Unexpected token < in JSON at position 0

So i want to fetch from my local data.js file. It looks like this:
{
product_name: [
{'name': 'hello',
'lastName': 'hello'
}, {'name': 'hi',
'lastName': 'hi'}
]
}
Is this valid JSON?
My code that I'm fetching it with looks like this :
fetch('./data.json')
.then(res=> res.json())
.then(text=> console.log(text))
After this, I get an error in my console.log. Also when I go to the network tab and click on data.json It tells me that javascript needs to be enabled, what does that mean? Thank you guys
I might be able to solve your answer.
First things
You must remember to format the JSON so that it is readable by a user, if you are currently developing your program. In production mode, you can skip this step, but it is a good practice.
Next, The JSON you have does not seem to use quotes for keys. This is a must for JSON.
If you don't like the quotes, use json5, JSON's friendlier brother.
Next,
This explains about JSON with fetch.
The Fetch API returns a response stream in the promise. The response stream is not JSON, so trying to call JSON.parse on it will fail. To correctly parse a JSON response, you'll need to use the response.json function. This returns a promise so you can continue the chain.
I see that you have done it, but are forgetting the GET method mentioned in the above post. And, use return keyword to pass the JSON to the next promise. So, your corrected JS code will be:
fetch('./data.json', { method: "GET" })
.then(res => return res.json())
.then(text => console.log(text))
I am not an expert in React, but these are some common things I can correct.
2nd Part of Question
I do not really know why it says JavaScript needs to be enabled. Maybe go to your settings and enable JavaScript? Or, if you use an ad-blocker, try disabling it once and see.
Final Words
I think I have solved a part of your question.

Processing fetch response - JS

I have the response after GET-request with fetch. I know that this response will return an Array. When I process it with .json() - everything is fine. But when I try to process same response with .formData()- it fails.
Here's the code:
fetch(fullPath)
.then(response => response.json())
.then((allData) => {
console.log(allData);
})
.catch((e) => console.log(e));
same one with response.formData() doesn't work.
So the question is - why we are not able to process the promise in first "then" with .formData() if the off. doc says that formData() is also acceptable method for extracting a body from the response ?
The formData() method will return an error if the response is not having the multipart/form-data type. It should have key=value entries. See this question where someone asks about designing a response with that format.
Something similar happens if you call the json() method on a response that is not valid JSON: that also triggers an exception.
Since multipart/form-data is rarely used as response content type, the formData() method is not often used either. The documentation on MDN mentions it has some use for service workers:
Note: This [method] is mainly relevant to service workers. If a user submits a form and a service worker intercepts the request, you could for example call formData() on it to obtain a key-value map, modify some fields, then send the form onwards to the server (or use it locally).

Node.js http.get xml is returned 'escaped'

I am working on a simple AWS Lambda function in Javascript (Node 6.x) which should 'proxy' an RSS of an italian news provider.
This is the code of the function:
var http = require("http")
exports.handler = (event, context, callback) => {
http.get("http://www.milanotoday.it/rss/", (response) => {
response.setEncoding("utf8")
let xml = ""
response.on("data", (chunk) => { xml += chunk })
response.on("end", () => { callback(null, xml) })
})
}
It works, or at least it loads the response inside the xml variable.
I can't get why the string is something like this:
"<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n<rss version=\"2.0\" xmlns:content=\"http://purl.org/rss/1.0/modules/content/\"...
It seems to be sort of 'escaped'.
Can somebody help me?
Thank you in advance...
http.get is probably working just fine. If you run your code outside of the AWS ecosystem, you'll see that you are getting unescaped XML from http.get. The problem is that Lambda wants you to return JSON so when you pass the string to the callback it gets escaped.
If you are running this function through API Gateway you can do a transform in the integration response. The way to do this is to return an object from your lambda:
callback(null, {myXML: xml}))
Then in the API Gateway go to the integration response area under your GET (or POST) resource and click the arrow next to the 200 response. This should reveal an area for body mappings. You want to add a mapping for application/xml and then add something like:
#set($inputRoot = $input.path('$'))
$inputRoot.myXML
This should get you nice clean XML. It's a little hard to describe so I'll post a screen shot that might help:
Double quotes have to be escaped inside a double quoted string (Makes sense, right?). Now you just have to parse the XML, using for instance xml2js

Using fetch() Webapi

I am trying to see how browser's native webapi fetch() api works. So far I have this: Sample-Code and it works fine. But what I don't understand why is it streaming string which I have to convert to a JSON? I am not sure why would anybody even need to stream a JSON as string through a REST API? I am pretty sure I am missing something here but I am not sure how I should tell fetch() to get the response as JSON and not as a ReadableByteStream which I have to convert to a string and parse it for a JSON.
My Question is this,
Why is a string being streamed here?
How do I tell fetch() to fetch my response as text or json so that I can do response.json() or response.text() as mentioned in the docs? (FYI I tried adding a header object and creating a Header instance and passing it to fetch() neither changed my response.
All you need to do is call
fetch("https://api.github.com/users/ajainarayanan").then(res => res.json());
Here is some modified code the has the same result
fetch("https://api.github.com/users/ajainarayanan")
.then(res => res.json())
.then(res => console.log('Profile: ', JSON.stringify(res, null, 2)));
Apparently I have to do response.json() in one then handler and have the actual value in subsequent then handlers. Update-code. What I didn't realize was response.json() returned another Promise which I should handle like a promise. So console.log(response.json()) will naturally just console log a JSON object instead of my actual json. Thank your #aray12 for you answer. I didn't realize the answer until I realize .json() returned a promise.
PS: Adding this as an answer as I couldn't add this in comments.

Categories