Eu criei uma API para estudar o consumo e etc, porém na hora de requisitar está me retornando esse erro:
Access to fetch at 'https://galaxies-api.herokuapp.com/galaxies' from origin 'http://localhost:3000' has been blocked by CORS policy: 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. App.js:42 GET https://galaxies-api.herokuapp.com/galaxies net::ERR_FAILED 200
Código da API:
const express = require('express');
const app = express();
const port = process.env.PORT || 5000;
const galaxies = require('./src/galaxies/galaxies.json');
app.get('/galaxies', (req, res) => {
return res.json(galaxies);
});
app.listen(port, () => {
console.log("Servidor online com sucesso!")
});
Ela está hospedada no Heroku
Código da aplicação para requisitar a API:
import React, { useState, useEffect } from 'react';
import styled from 'styled-components';
import './reset.css';
function App() {
const Container = styled.div`
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
`;
const Header = styled.header`
height: 6vh;
width: 100%;
display: flex;
justify-content: center;
align-items: center;
background-color: #25254c;
color: #fff;
font-size: 12px;
h1 {
cursor: pointer;
letter-spacing: 2px;
font-weight: 300;
}
`;
const Section = styled.section`
padding: 30px;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
img {
border-radius: 10px;
margin: 5px;
}
`;
useEffect(() => {
let url = "https://galaxies-api.herokuapp.com/galaxies";
fetch(url)
.then((resultado) => resultado.json())
.then((json) => {
console.log(json);
});
}, []);
return (
<Container>
<Header>
<h1>Galáxias</h1>
</Header>
<Section>
...
</Section>
</Container>
);
}
export default App;