Promise chain fetch back Array (0) - javascript

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))
});

Related

How to get and supply API access key to successfully fetch the API?

Trying to grab and manipulate currency exchange data. Can't figure out how to access the API key and integrate it into the code.
Here is JS code:
document.addEventListener('DOMContentLoaded', function() {
fetch('https://api.exchangeratesapi.io/latest?base=USD')
.then (response => response.json())
.then (data => {
console.log(data);
});
});
Console output:
{success: false, error: {…}}
error: {code: 101, type: 'missing_access_key', info: 'You have not supplied an API Access Key. [Required format: access_key=YOUR_ACCESS_KEY]'}
success: false
Normally the API docs shd show you how to use the API key, from my experience in React and Node, the API key is treated as an env variable and then you chain it into your request URL, so when you make your request you are authenticated and then sent a response.
Something like this:
document.addEventListener('DOMContentLoaded', function() {
fetch('https://api.exchangeratesapi.io/insertAPIkeyHere/latest?base=USD')
.then (response => response.json())
.then (data => {
console.log(data);
});
});
// do refer to the docs for an idea of how they want the key utilised, but it shouldn't be to complex
Thanks for everyone's feedback. Got it to work by carefully reading the documentation which signaled that I used an old URL from a dated course, and headers were needed in this case.
Here is the update:
var myHeaders = new Headers();
myHeaders.append("apikey", "API_KEY_HERE");
var requestOptions = {
method: 'GET',
redirect: 'follow',
headers: myHeaders
};
fetch("https://api.apilayer.com/exchangerates_data/latest?&base=EUR", requestOptions)
.then (response => response.json())
.then (data => console.log(data))
.catch(error => console.log('error', error));

React get image from api using fetch

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.

How to return a response from a fetch in javascript

I am having trouble returning the response for a API call in my React Native project.
let response = fetch('http://3.133.123.120:8000/auth/token', {
method: "POST",
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
client_id: 'NTMtzF7gzZPU9Ka35UFsDHvpR8e4D1Fy4OPRsurx',
grant_type: 'password',
username: user,
password: pass,
})
})
.then((response) => response.json())
.then((response) => this.setState({jsonData: response}))
.then(() => alert('resposne jsonData: ' + JSON.stringify(this.state)));
alert('resposne jsonData: ' + JSON.stringify(response))
The code above returns the correct response in the bottom .then() statement, however, I have not been able to use the data outside of the fetch() statement.
Anything I've tried to use outside of the fetch() (like my alert in bottom line) has given me the following...
{"_40":0,"_65":0,_55":null,"_72":null}
Please also note this is all inside a React class Component
fetch returns a Promise: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API
You already have access to the value in that final then. If you're looking for a way to use the value below without using a callback, you could consider async/await style and wrapping this code in a function like so:
const fetchData = async () => {
const results = await fetch() // put your fetch here
alert(results.json());
};
fetch info:
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API
async/await info:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await

Accessing promise data from Node API inside React fetch call

I'm putting together a React app that consumes data from a Node/Express REST API which is currently on my local machine. I've got a simple res.json returning a Sequelize object, and I'm accessing it through a service I made. Obviously, I'm going to be putting the object in state eventually, but I'm currently having difficulty accessing the values.
const options = {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded"
},
body: JSON.stringify({email: "matthewharp#gmail.com", password: "M1nerals"})
};
fetch('http://localhost:3000/users/sign_in', options)
.then(response => console.log(response.json()));
I'm getting the results in the console, but they're stuck in the [[PromiseValue]].
I must be missing some kind of async step, but I'm not sure what.
The json method returns a promise, which you also need to await. So do:
fetch('http://localhost:3000/users/sign_in', options)
.then(response => response.json())
.then(obj => console.log(obj));
You're having this error because response.json() return a promise.
you need to do
fetch('http://localhost:3000/users/sign_in', options)
.then(response => response.json())
.then(res => console.log(res));
You need to return the promise from the fetch call or else you need to act on it in the then for the json promise.
const options = {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded"
},
body: JSON.stringify({email: "matthewharp#gmail.com", password: "M1nerals"})
};
return fetch('http://localhost:3000/users/sign_in', options)
.then(response => {
console.log(response.json())
return response.json()
}
);
or...
const options = {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded"
},
body: JSON.stringify({email: "matthewharp#gmail.com", password: "M1nerals"})
};
fetch('http://localhost:3000/users/sign_in', options)
.then(response => {
console.log(response.json())
response.json().then( result => {
// whatever you're doing with the data here.
}
);
Take a look at the fetch api:
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
You need a separate then chained to take the json data once ready, and it will give you the values.
('http://localhost:3000/users/sign_in', options)
.then(function(response) {
return response.json();
})
.then(function(myJson) {
console.log(JSON.stringify(myJson));
});

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) });

Categories