Hi i want to fetch data from avascan api and display it in html, but i am not able to do this. I have tried fetch api, json and ajax ways but none worked for me. Any suggestions? This is my html https://avascan.info/api/v1/home/statistics
const api_url = 'https://avascan.info/api/v1/home/statistics';
async function getAVA() {
const response = await fetch(api_url);
const data = await response.json();
const {
blockchains,
validators
} = data;
document.getElementById('lat').textContent = blockchains.toFixed(2);
document.getElementById('lon').textContent = validators.toFixed(2);
}
getAVA();
setInterval(getAVA, 1000);
<h1>What the stats?</h1>
<p>
blockchains: <span id="lat"></span>°<br /> validators: <span id="lon"></span>°
</p>
<div id="issMap"></div>
You are getting a CORS protection error, as mentioned before.
However it seems you need to use a GraphQL API: https://graphql.avascan.info/
Look at this quick example:
async function getAVA() {
fetch('https://graphql.avascan.info', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
query: `
query {
stats {
priceAvaxUsd,
connectedNodes
}
}`
}),
})
.then((res) => res.json())
.then((result) => console.log(result));
}
getAVA();
Looks like you have this error: No 'Access-Control-Allow-Origin' header is present on the requested resource.
This is a CORS protection and you may need certain requirements to fetch this dat such an api key, or update configuration your options in the fetch method
Here is a resource to help
Related
I need to POST to a third party api route to receive an access token to be authorized to fetch data from their endpoints, but I'm not sure how to use the token. They are using Swagger:
export default async function() {
const res = await fetch('url', {
method:'POST',
headers: {
accept: 'application/json'
}
});
const data = await res.json()
console.log(data)
}
I get in response:
{
access_token: 'my token...',
...
}
But I'm not sure how I'd use this response to authorize fetching data. Do I need to pass the token to the headers in the fetch?
export async function getStaticProps() {
const res = await fetch( `url`, {
headers: {
accept: 'application/json',
}
});
const data = await JSON.stringify(res);
return {
props: {
items: data
},
};
}
I can't seem to find much info on this, or I'm just searching for the wrong things. I'm not sure if I'm understanding this correctly
Likely you'll need to send that token in an Authorization header with the request, something like this:
const res = await fetch(`url`, {
headers: {
accept: 'application/json',
Authorization: `Bearer ${token}`,
}
});
const json = await res.json()
const data = JSON.stringify(json);
The API docs should be able to tell you specifics though, if you're still having issues please post the API docs if they're public!
I am using Next.js api route to handle a POST request then send a response back to the frontend. I have used Rapid API client extension to confirm there is a response being sent to the frontend. I just dont know how to handle it in the frontend.
Here is the code on the api route:
import clientPromise from "../../../config/mongodb";
export default async function userDetailsHandler(req, res) {
const body = req.body;
if (req.method == "POST") {
const client = await clientPromise;
const db = client.db("mood-board");
let emailQuery = await db
.collection("users")
.find({ email: body.email })
.limit(1)
.toArray();
let parsedData = JSON.parse(JSON.stringify(emailQuery));
res.status(200).json(parsedData)
console.log(parsedData)
} else if(req.method = "GET") {
}
}
In the following example, you use the fetch api to post the data which returns a promise. You can use then() which takes a callback function that you can use to operate on the data once that promise is returned.
Example:
useEffect(() => {
// POST request using fetch inside useEffect React hook
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title: 'React Hooks POST Request Example' })
};
fetch('https://reqres.in/api/posts', requestOptions)
.then(response => response.json())
.then(data => setPostId(data.id));
// empty dependency array means this effect will only run once (like componentDidMount in classes)
}, []);
I am trying to call a Freesound API. Fetch throws an Unauthorised error whereas Postman works.
Code
const BASE_URL = "https://freesound.org/apiv2/sounds/";
const rain = "58835";
const APIKEY = "foo";
const headers = {
method: "GET",
headers: {
'Authorization': `Token ${APIKEY}`,
},
mode: "no-cors",
};
fetch(BASE_URL + rain, headers)
.then((response) => response.json())
.then((json) => console.log(json))
.catch((err) => console.log(err));
First of all, you should never post API Key on any public platform as anyone can access and exploit the API that you would have paid for.
Solution
The endpoint you're using seems to be invalid. Also, don't use mode: 'no-cors' unless an opaque request serves your need. Else, you won't be able to access any property in the response object.
Reason of 401 error: Using no-cors prevents Authorization header to be added in your request.
Getting past CORS error: It usually happens in localhost during development. You can use an extension which would allow CORS.
const QUERY = 'piano';
const API_KEY = 'foo';
const BASE_URL = `https://freesound.org/apiv2/search/text/?query=${QUERY}`
const headers = {
method: 'GET',
headers: {
Authorization: `Token ${API_KEY}`,
}
};
fetch(BASE_URL, headers)
.then((response) => response.json())
.then((json) => console.log(json))
.catch((err) => console.log(err));
I'm trying to grab data from my component state and than send that to a REST api. I make the axios post req in an on submit function, however I know this won't work in gatsby.My res.data is "This app works best with Javascript" when I make the request from the onSubmit function from Gatsby. I was wondering what was the best way I can make the post request from Gatsby so that I can pass in the data from the component's state. I have been looking into using this as my gatsby-node.js file however I'm not sure how I can get the component's state data in there so I can use it in the post req. Thanks.
onSubmit Function
//submits answers to backend
Submit = () => {
let {answers} = this.state
axios
.post("/done", answers)
.then(res => this.setState({results:res.data,resultsStatus:true}))
.catch(
err => console.log(err)
);
};
To fire the submit function I have a loading gif popup for 4 seconds and then I fire the submit function. Content request is that jsx being returned by the component
contentQuest = (
<div className = 'results-loading'>
Loading Results!
<img src={require('./images/loading.gif')} className='results-loading-gif'/>
</h2>
</div>
);
setTimeout(() => {
this.Submit()
},4000)
gatsby-node.js
// You can delete this file if you're not using it
const axios = require('axios');
const crypto = require('crypto');
exports.sourceNodes = async ({ boundActionCreators }) => {
const { createNode } = boundActionCreators;
// fetch raw data from the randomuser api
//Here I'm trying to change it to axios.post and grab component's state data
//not sure how to
const fetchRandomUser = () => axios.get(`https://randomuser.me/api/?results=500`);
// await for results
const res = await fetchRandomUser();
// map into these results and create nodes
res.data.results.map((user, i) => {
// Create your node object
const userNode = {
// Required fields
id: `${i}`,
parent: `__SOURCE__`,
internal: {
type: `RandomUser`, // name of the graphQL query --> allRandomUser {}
// contentDigest will be added just after
// but it is required
},
children: [],
// Other fields that you want to query with graphQl
gender: user.gender,
name: {
title: user.name.title,
first: user.name.first,
last: user.name.last,
},
picture: {
large: user.picture.large,
medium: user.picture.medium,
thumbnail: user.picture.thumbnail,
}
// etc...
}
// Get content digest of node. (Required field)
const contentDigest = crypto
.createHash(`md5`)
.update(JSON.stringify(userNode))
.digest(`hex`);
// add it to userNode
userNode.internal.contentDigest = contentDigest;
// Create node with the gatsby createNode() API
createNode(userNode);
});
return;
}
Edit:
I tried changing my post request to this
fetch('http://localhost:5000/api/done', {
method: 'POST',
body: JSON.stringify(answers),
headers : {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
}) .then(res => {
return res.json()})
.then(res => console.log(res))
.catch(
err => {
console.log(err)}
);
};
Now I have this message in my console:
Access to fetch at 'http://localhost:5000/api//done' from origin 'http://localhost:8000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
So it turns out I needed to include this in my server file.
app.use(function(req, res, next) {
res.header(`Access-Control-Allow-Origin`, `http://localhost:9000`)
res.header(`Access-Control-Allow-Credentials`, true)
res.header(
`Access-Control-Allow-Headers`,
`Origin, X-Requested-With, Content-Type, Accept`
)
next();
});
I am trying to integrate coinmarketcap api but cannot really get the data. I registered, got the API key, and wrote the following method to fetch the data:
let getPostsList = async () => {
const options = {
method: 'GET',
headers: {
'X-CMC_PRO_API_KEY': 'api-key-goes-here'
},
mode: 'no-cors'
};
try {
const response = await fetch(`https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest`, options);
const json = await response.body;
// console.log(json)
return json
} catch (err) {
console.log('Error: ', err)
}
};
All I get is 401 error, like this:
GET https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest
401
Any suggestions what I should fix? Docs says that 401 is likely connected to API key, but they say to provide it in the headers like the above...
From what I've tested after getting my own API key, the no-cors mode is problematic. You will need to use CORS, where https://cors-anywhere.herokuapp.com/ comes into handy.
Just send the request like this :
const options = {
method: 'GET',
headers: {
'X-CMC_PRO_API_KEY': 'api-key-goes-here'
},
};
try {
const response = await fetch(`https://cors-anywhere.herokuapp.com/https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest`, options);