How to Parse JSON Array Response when using Axios - javascript

I want to get all string on https://animechan.vercel.app/api/available/anime but suddenly i can't get it, anyone would help me?
heres my code:
axios.get('https://animechan.vercel.app/api/available/anime')
.then(response => {
console.log("Source of Anime Qoutes: \n\n\n" + JSON.parse(response.data));
})
.catch(error => {
console.log(error);
});

Axios automagically deserializes the response body from JSON to a Javascript object, assuming the response's content type is application/json or you tell Axios to do so regardless. See the documentation at
https://axios-http.com/docs/intro
All you should need is:
var axios = require("axios");
axios.get( 'https://animechan.vercel.app/api/available/anime' )
.then( response => {
console.log(`Source of Anime Qoutes:`);
console.log( response.data.join('\n') );
})
.catch(error => {
console.log(error);
});

Related

How to use the value of a response from a GET request once the request is finished in React? [duplicate]

I am new to React and API request calls.
I have created a basic React App. I have a requirement to display the data by calling an API.
I am able to retrieve the data in the console, but finding difficult to display it on the browser.
Here is the data which I need to display :
Console Data
Here is the code that I have written (generated from Postman):
import React from "react";
class FetchRandom extends React.Component {
render() {
var myHeaders = new Headers();
myHeaders.append(
"Authorization",
"Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik1yNS1BVWliZkJpaTdOZDFqQmViYXhib1hXMCIsImtpZCI6Ik1yNS1BVWliZkJpaTdOZDFqQmViYXhib1hXMCJ9.eyJhdWQiOiIwMDAwMDAwMy0wMDAwLTBmZjEtY2UwMC0wMDAwMDAwMDAwMDAvY29vcG9ubGluZS5zaGFyZXBvaW50LmNvbUA4MzRmYjdiNC02MjRkLTRkZTgtYTk3Ny0yZDQ2YWQ5NzliZDkiLCJpc3MiOiIwMDAwMDAwMS0wMDAwLTAwMDAtYzAwMC0wMDAwMDAwMDAwMDBAODM0ZmI3YjQtNjI0ZC00ZGU4LWE5NzctMmQ0NmFkOTc5YmQ5IiwiaWF0IjoxNjQ1MDg1NjQ3LCJuYmYiOjE2NDUwODU2NDcsImV4cCI6MTY0NTE3MjM0NywiaWRlbnRpdHlwcm92aWRlciI6IjAwMDAwMDAxLTAwMDAtMDAwMC1jMDAwLTAwMDAwMDAwMDAwMEA4MzRmYjdiNC02MjRkLTRkZTgtYTk3Ny0yZDQ2YWQ5NzliZDkiLCJuYW1laWQiOiJhMDFkNGE5Yi1mZGE2LTQ2ZTQtOTE3NC02NjFhNjY3M2FjZGNAODM0ZmI3YjQtNjI0ZC00ZGU4LWE5NzctMmQ0NmFkOTc5YmQ5Iiwib2lkIjoiMGU4ZDY3NjQtM2JjNS00MDg2LTgxOGUtZGU3N2VlODYyOTc4Iiwic3ViIjoiMGU4ZDY3NjQtM2JjNS00MDg2LTgxOGUtZGU3N2VlODYyOTc4IiwidHJ1c3RlZGZvcmRlbGVnYXRpb24iOiJmYWxzZSJ9.ge789TPniLEXtK_2zuMqZzOgLM6z1arpC5CEDAGB9J3VoEllwKCEXtlL-jzCo45aLD6VOanIbWUugdFuGXeBgeuCSV9PYRGSX9qmf5sWWvGqGM3InLq6-xHtUUE56cq9EQI634jfytq8XhUO3uLXj9x3J5rumY4WH1E0LEivCCy2A02iGmxFHsa6uTC1Iy1K_wJ4jIqlf3KRU8h0rO6HSmx2uPDeVM7KtMRFanWMgYrGUzBIk5Yh-kFCfdXFftPA_VQQGBP4A_I_3LVlbwWkvoiUmNBQYDf55Oh6onp0aDDRxViCCHcclICGGjUhh1j6fnQMmJZwOpVv7GEOKnpB1g"
);
myHeaders.append("Accept", "application/json;odata=verbose");
var requestOptions = {
method: "GET",
headers: myHeaders,
redirect: "follow",
};
fetch(
"https://cooponline.sharepoint.com/sites/TestDemoFeb/_api/web/lists/getbytitle('TestPost')/GetItembyID(4)",
requestOptions
)
.then((response) => response.text())
.then((data) => console.log(data))
.catch((error) => console.log("error", error));
return <div></div>;
}
}
export default FetchRandom;
Could anyone please help me with it?
you can use the concept of states to achieve this in an easy way.
just create a stete like this:
const [data, setData] = useState();
// ///////////////////////////////////////
// in your fetch you can write something like this:
fech("your URL")
.then(res => res.json())
.then(data => {
setData(data);
})
.catch(error => {
setData("An Error Happened: ", error);
})
// /////////////////////////////////////////
then in your returned component, use it by adding curly braces and your state - here is data for example - and you're done!
also you can use some better and elegant thing like conditioanl rendering and so on for better showing.

Accessing response in case of Error when using fetch API

I am using following fetchProtectedResource call to a REST Service:
return this.fetcher.fetchProtectedResource(url, {
method: 'PUT',
body: body
}, config)
.toPromise()
.then(response => response.json()
)
.catch(e => {
//How to get json from e object????
return null;
});
I can see in Browser that in case of error, the server return json in response but I cant find any documentation about the structure of this error Object to get this JSON.

Why Axios response doesn't console log result?

I'm working on an backend API but at some point I need to get user data from another API. I am trying to use Axios to make http request in order to do that. The request return the result in the browser as expected but the problem is that I can't display console log in the terminal. It doesn't show anything even though I asked the program to do so. Is there a problem probably with my code?
Here is my code :
const axios = require('axios');
const AxiosLogger = require('axios-logger');
const instance = axios.create();
module.exports = (router) => {
router.get('/profile', function(req, res) {
//random fake profile info
axios.get('https://randomuser.me/api/')
.then(response => {
console.log(response.data);
console.log(response.data);
return response.data
})
.catch(error => {
console.log(error);
});
});
};
I would suggest trying response.send to forward the axios response to your client like so:
module.exports = (router) => {
router.get('/profile', function(req, res) {
//random fake profile info
axios.get('https://randomuser.me/api/')
.then(response => {
console.log(response.data);
// Send the axios response to the client...
res.send(response.data)
})
.catch(error => {
console.log(error);
});
});
};

Saving data from JSON end point

I am trying to map over the returned json and save the id into profile/profiles. However it does not seem to be mapping over the the data correctly, id: ${ profile.id } this bit needs to be changed? Any help is much appreciated.
Is their a online tool that can help with me this?
API request:
// Grabs company data from the json url
private getProfiles() {
let config = {
headers: {'Authorization':'Bearer AQVVEqNXTWVYPpPYivKNWVO8jsTx2eveV3kBg'}
}
axios
.get("https://cors-anywhere.herokuapp.com/" + "https://api.linkedin.com/v2/me", config)
.then(response =>
response.data.map(profile => ({
id: `${ profile.id }`
}))
)
.then(profiles => {
this.setState({
profiles
});
})
// We can still use the `.catch()` method since axios is promise-based
.catch(error => this.setState({ error, isLoading: false }));
}
Json data returned:
{
"localizedLastName": "King",
"id": "fm0B3D6y3I",
"localizedFirstName": "Benn"
}
When I console log the response.data
If the only data returned from your endpoint is the JSON you posted, then you don't have an array to map over.
You have a single object.
I've never used the axios library before, but looking at the source code response.data should be the JSON-parsed responseText from the XHR request:
https://github.com/axios/axios/blob/4f189ec80ce01a0275d87d24463ef12b16715d9b/lib/adapters/xhr.js#L51-L53
https://github.com/axios/axios/blob/4f189ec80ce01a0275d87d24463ef12b16715d9b/lib/defaults.js#L61
And now I see that you have posted response.data and it matches what I'd expect.
With that in mind I'd suggest handling it like this:
// Grabs company data from the json url
private getProfiles() {
let config = {
headers: {'Authorization':'Bearer AQVVEqNXTWVYPpPYivKNWVO8jsTx2eveV3kBg'}
}
axios
.get("https://cors-anywhere.herokuapp.com/" + "https://api.linkedin.com/v2/me", config)
.then(response => ({
id: profile.id
}))
.then(profiles => {
this.setState({
profiles
});
})
// We can still use the `.catch()` method since axios is promise-based
.catch(error => this.setState({ error, isLoading: false }));
}
What you're getting back is a single profile though. If you need profiles to be an array you'll need to put the response in an array.
I don't get it, what you are trying to do. In the map you have a callback function, but as I see you wrote there an object. If you are wanting to rewrite the current profile's id then write this:
response.data.map(profile => ({
profile.id = `${ profile.id }`;
}))
But if you want it to make a variable then this:
response.data.map(profile => ({
let id = `${ profile.id }`;
}))

Fetch() API not updating JSON file

I have a JSON file I want to read from and write to that looks like this:
[
"test#example.com"
]
I want to add info to this file using the fetch() API. So far, I can only read from this file.
let handle = JSON.stringify(`test#example2.com`); // handle is fine irrelevant of "" or ``
const url = `../json/emails.json`; // URL is fine
const options = {
method: `POST`, // PUT return error at second fetch: SyntaxError: "JSON.parse: unexpected character at line 1 column 1 of the JSON data"
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: handle
};
fetch(url) // this fetch is fine
.then(response => {
if (!response.ok) {
throw new Error(`Error getting the stuff`);
}
return response;
})
.then(r => r.json())
.then(data => {
console.log(`Data: ` + data);
});
fetch(url, options)
.then(response => {
if (!response.ok) {
throw new Error(`Error getting the stuff`);
}
return response;
})
.then(a => a.json())
.then(append => {
console.log(`Data updated: ` + append);
}).catch(err => {
console.error('Request failed: ', err);
});
I get no errors (aside from that PUT comment); ESLint and TSLint don't have any problem with the JS file nor with the JSON file. What am I doing wrong?
fetch() is an API for making HTTP requests.
It can't write to files. In particular, nothing can write to arbitrary URLs. (Imagine if it was possible for any browser to write new data to http://www.google.com/!)
If you want your PUT or POST request to change data on your server, then you must write server-side code to process the request and edit the file.

Categories

Resources