I am using this API https://api.cryptonator.com/api/ticker/btc-usd If I paste this in the browser it works fine, and gives the required JSON.
But when I call from my react application, it throws CORS error, which is bypassed by using.
fetch('https://api.cryptonator.com/api/ticker/btc-usd', {
mode: 'no-cors', // 'cors' by default
})
.then(res => res.json())
.then(res => {
console.log(res);
})
.catch(err => {
console.log(err)
})
But now it gives 503 error. I tried the same in postman, it didn't work at first, but when I copied the 'User-Agent' and 'Cookie' field from the browser network tab to postman it did work on postman too.
I tried doing the same thing in react, it says 503. I even copied the entire fetch request from network tab, it still shows 503.
Anyone who can help on this will be much appreciated.
Edit:
I even tried adding proxy in package.json like
"proxy": "https://api.cryptonator.com", and called the API like fetch(/api/ticker/btc-usd) but still does not get resolved.
Thanks for your last comment. It is important to look for an answer for an error exactly with the error's description. The solution or its part is often in error description. Here you have: "FetchError: invalid json response body at Unexpected token < in JSON at position 0" so try like this in your component: without hooks:
componentDidMount() {
let url = "https://api.cryptonator.com/api/ticker/btc-usd";
fetch(url)
.then((money) => money.json())
.then((money) => {
console.log("resultat = ", money);
this.setState({
coin: money.bodies,
});
});
}
and if you use hooks you can do it like this:
import React, { useState, useEffect } from 'react';
function App() {
const [data, setData] = useState([]);
useEffect(() => {
const fetchData = async () => {
const response = await fetch(
'https://api.cryptonator.com/api/ticker/btc-usd',
);
const json = await response.json();
setData(json.hits);
};
fetchData();
});
return (
<ul>
{data.map(coin => (
<li key={coin.tricker.base}>
<a href={coin.tricker.price}>{coin.tricker.target}</a>
</li>
))}
</ul>
);
}
export default App;
this is only an example. Good luck with your application
You need to use npm cors in your backend.
$ npm install cors
and you have an example of how to use it with node and express.
var express = require("express");
var cors = require("cors");
var app = express();
app.use(cors());
app.get("/products/:id", function (req, res, next) {
res.json({ msg: "This is CORS-enabled for all origins!" });
});
app.listen(3000, function () {
console.log("CORS-enabled web server listening on port 3000");
});