Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

395
Visualizações
cryptonator api 503 when running in react, but works fine when called from browser

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.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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

about 4 years ago · Juan Pablo Isaza Relatório

0

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");
});
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda