I am trying to fetch some data from the server and I am using react.js
and the fetch api but a get that
SyntaxError: Unexpected token < in JSON at position 0
this is my code for fetching the data
componentDidMount() {
// fetch all categories from the server
fetch('http:localhost:5555/categories')
.then(res => res.json())
.then(categories => {
this.setState({ loading: false });
console.log(categories);
this.setState({ categories });
})
.catch(err => {
this.setState({ loading: false });
console.log(err);
});
}
any thoughts
I think the problem is in your fetch method and you write the url in the wrong form
try to change the url from
http:localhost:5555/categories
to
http://localhost:5555/categories
any try to fetch again
Related
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);
});
i am getting the data from my rails API backend and what i want to do is reload that get request every 15s , so if something changes on a backend ( for example i make a post request to my backend in another route) it reloads and gets the current data .
My created :
created() {
if (!localStorage.signedIn) {
this.$router.replace("/");
} else {
this.$http.secured
.get("/api/v1/records")
.then(response => {
console.log(response.data);
this.records.splice(0, this.records.length - 1, ...response.data);
})
.catch(error => this.setError(error, "Something went wrong"));
this.$http.secured
.get("/api/v1/templates")
.then(response => {
this.templates = response.data;
})
.catch(error => this.setError(error, "Something went wrong"));
this.$http.secured
.get("/api/v1/data")
.then(response => {
this.datas = response.data;
})
.catch(error => this.setError(error, "Something went wrong"));
}
},
Could you help me with implementing a setInterval to my get requests?
thanks
Try to use the setInterval, like:
mounted() {
this.intervalData = setInterval(this.getdata, 15000)
},
destroyed() {
clearInterval(this.intervalData)
},
methods: {
getData() {}
},
More smart solution could be: use POST request in nuxt proxy server or in your backend, like axios.post('/data', payload) and connect the websockets, you can use pusher for that. The final logic is: user add some data => post to server => server emits the websockets event => vuex listen to the event and the data will be reactive in all tabs.
I am testing my NodeJS backend using Insomnia and while it does work no problem in Insomnia I am getting a 500 error on the frontend every time. I was wondering if anyone maybe knew where this could be coming from if like I said it works just fine on my the endpoint testing program. Since it is a 500 error it is not very descriptive. Links can be shared if needed
const handleSubmit = e => {
e.preventDefault();
console.log("cred username", creds.username);
axios
.post("https://exampleapi/api/login")
.then(res => {
console.log(res.data);
localStorage.setItem("token", res.data.access_token);
props.history.push("/");
})
.catch(err => console.log(err.response)); };
So I figured it out it was an error in my post request would should have been included was
const handleSubmit = e => {
e.preventDefault();
console.log("cred username", creds.username);
axios
.post("https://mystery-doggo.herokuapp.com/api/login", creds)
.then(res => {
console.log(res.data);
localStorage.setItem("token", res.data.payload);
props.history.push("/");
})
.catch(err => console.log(err.response));
};
"creds" after the link and change res.data.access_token to res.data.payload
I trying to view status of a variable (salesforecasting) in database. Its responds by sending true or false which is received fine in Postman. However when it gets to react, it is shows undefined on console. if i see whole response object, there i can see value has return correctly but when i try to print it, it shows undefined.
in routes/api/salesforecasting.js
router.post('/view', function(req, res) {
const email="Hamzakhan003#gmail.com"
Customer.findOne({Email:email})
.then(data=>{
if(data){
let salevalue=data.Salesforecasting
res.send({
value: salevalue
});
}
});
});
in react file
componentDidMount(){
return axios.post('http://localhost:3000/api/sales-forecasting/view')
.then(response => {
//const output = response.value
const value = response.value;
{console.log(arr.value)}
this.setState({
added: value
});
});
}
I think u need to check in response.data.value instead of response.value.
axios populates the entire server response in response.data
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 }`;
}))