React get image from api using fetch - javascript

I need to get an image using the fetch api. My colleague said that the call to the server should return a base64 string to display the image. The image needs to be authenticated and I cant just use its url. This is what I have:
fetch(`${apiUrl}filestore/${logo.name}`, {
.then(res => console.log(res)
Im not really sure how to get the base64 string. Apparantly im not using fetch right. Here is what is displayed in the console,
![screenshot image][1]

Try to format the res to json. Then check the res.
fetch(`${apiUrl}filestore/${logo.name}`, {
method: 'GET',
headers: {
Authorization: JSON.parse(localStorage.getItem('Hidden'))
? `Bearer ${JSON.parse(localStorage.getItem('Hidden')).access_token}`
: '',
},
})
.then(res => return res.json())
.then(res => console.log(res))

Here is the Link to mdn documentation for Fetch API - https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
fetch('http://example.com/movies.json')
.then(response => response.json())
.then(data => console.log(data))
.catch(e => console.log("error", e);
considering your response is of JSON type - Link to find the supported body instances - https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#Body
Try console.log(typeof response); to find out what your response type is so you can set the body instance in .then(response => response.json() or response.text() etc.,)
Make sure you catch the error too.

Related

Promise chain fetch back Array (0)

I've tried promise chaining, where my chained var is valid, and my fetch is working with manually key-in data, but I can't get it work by putting the var, the return console log shown blank value
{"code":"success","message":null,"data":[]} or
{"code":"success","message":null,"data":[Array(0)]}.
Any suggestions on what I did wrong in my code?
function anExportFunction(){
fetch(an_API_URL_01,{
method: 'GET',
}).then(function(response) {
return response.text();
})
.then(function(dataIds) {
return fetch(an_API_URL_02,{
method: 'POST',
body: JSON.stringify({
"elementIds" : ['dataIds'],
})
})
.then(response => response.text())
.then(data=> console.log(data))
});
Whereby, the manual input that make this fetch response work with the server is as follow
"elementIds" : ["0001","0002","0003",...]
The console.log(dataIds) is as {"code":"success","message":null,"data":["0001","0002","0003",...]}
I have managed to make a few twerk with the advices provided from both #Nick & #Nisala! Thanks both of the experts providing ideas to contribute the success of solving this!
The key of the problem is that the response fed back from the service provider server is always consist of a few criterions including earlier mentioned Code, Message and Data {"code":"success","message":null,"data":["0001","0002","0003",...]}
In order to feed exact data only content, it is necessarily to filter out the unwanted data, and assure the JSON content feeding the second fetch request, not a JSON.stringify content.
Therefore, the Promise Chain should have been built as below
function anExportFunction(){
fetch(an_API_URL_01,{
method: 'GET',
}).then(response => response.json())
.then(retrieveId => {
const dataIds = retrieveId.data;
return fetch(an_API_URL_02,{
method: 'POST',
body: JSON.stringify({
"elementIds" : dataIds,
})
})
.then(response => response.text())
.then(data=> console.log(data))
});

Javascript `Fetch` in React native returns unexpected Identifier when passing query to the URL String

I am trying to consume an API created using PHP in an expo Application.
But I keep having the error JSON Parse error: Unexpected identifier "top" no matter what I've tried.
My final attempt :
const data = { action: "top" };
fetch(
`http://.../get.php?action=${encodeURIComponent(
data.action
)}`,
{
method: "GET",
}
)
.then((res) => res.json())
.then((res) => {
console.log(res);
})
.catch((err) => console.log(err));
I have also tried the searchParams approach which gave me the same result.
What I am missing here.
Thanks.

How would I create a div and place the 'brands' data from JSON into it?

Currently, I'm trying to learn how to access data from an API and place it into a div onto my html. I'm using fetch, but I'm not sure where to go after I stringify the data. I want to access the 'Brands' data from the API and place it into my html.
fetch("http://makeup-api.herokuapp.com/api/v1/products.json")
.then(res => res.json())
.then(
(data) => {
JSON.stringify(data)
}
I recommend using this tutorial to learn JavaScript fetch.
Here's a working snippet (although it won't work from SO).
const url = 'http://makeup-api.herokuapp.com/api/v1/products.json';
fetch(url)
.then((resp) => resp.json())
.then(function(data) {
let products = data;
return products.map(function(product) {
console.log(product.brand);
//$("#listOfBrands").append(product.brand); // do as you will
})
})
.catch(function(error) {
console.log(error);
});
<div id="listOfBrands"></div>

Can i post text data using fetch in react

I'm using react js and I want to post text and return a text.
Can anyone help me in posting text and receiving text? I have used
content type text/plain but that didn't help.
Is there any way to do?
const options = {
method: "POST",
headers: {
"Content-Type": "text/plain"
},
body: this.state.url
}
fetch("http://localhost:3000/messages", options)
.then(response => response)
.then(data => {
console.log(data)
this.setState({
code: data
});
});
This is what I have tried to get the text value from api
I am getting an error as
Uncaught promise typeError failed to fetch
fetch returns a "promise" for a Response object which has promise creators for json, text, etc. depending on the content type. So the code should be changed to.
Also consider adding a catch block for the promise in case of errors and check the console output error (if any ).
const options = {
method: "POST",
headers: {
"Content-Type": "text/plain"
},
body: this.state.url
}
fetch("http://localhost:3000/messages", options)
.then(response => response.json()) // or response.text()
.then(data => {
console.log(data)
this.setState({
code: data
});
})
.catch(err => { console.log('error while fetching', err) });

Using fetch to get data from an API in React

In Panel.js how can I get data from an API that I wrote in index.js?
Panel.js
index.js
ProfilePanel.js
You can use javascript fetch API
GET example
fetch(`https://jsonplaceholder.typicode.com/posts?key=${key}&results=${results}`)
.then((res) => { return res.json() })
.then((data) => {
console.log(data)
});
})
}
POST example
let key = 'key'
let results = 12;
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers : new Headers(),
body:JSON.stringify({key: key, results: results})//use property short hand here
}).then((res) => res.json())
.then((data) => console.log(data))
.catch((err)=>console.log(err))
you already get the response and you map the response to state 'results'.you can dispaly the data by simply writing "this.state.results"

Categories