Using API in React JS

Asked

Viewed 835 times

1

I’m new to Reactjs and I’m learning about API. I’m trying to use a Star Wars API, but it’s not paying off. I’ve used others and they worked.

This is my App.js file:

import React, { Component } from 'react';
import api from './api';

class App extends Component {

  state = {
    filmes: [],
  }

  async componentDidMount() {
    const response = await api.get('films');

    this.setState({ filmes: response.data });

    console.log(this.state.filmes);
  }

  render() {

    const { filmes } = this.state;

    return (
      <div>
        <h1>Listar os Filmes</h1>
        {filmes.map((filme) => (
          <div class="card">
            <div class="card-body">
              <h2 class="card-title">{filme.results.title}</h2>
              <h3 class="card-episode">{filme.results.director}</h3>
              <h4 class="card-date">{filme.results.release_date}</h4>
              </div>
              </div>    
        ))}
      </div>
    );
  };
};

export default App;

And this is my api.js file

import axios from 'axios';

const api = axios.create({
    baseURL: 'https://swapi.dev/api/'
});

export default api;

This is the api link: https://swapi.dev/api/films/

The mistake I get is:

Access to Xmlhttprequest at 'https://swapi.dev/api/films' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested Resource.

Failed to load Resource: net::ERR_FAILED

Uncaught (in Promise) Error: Network Error creatat eError (createError.js:16) At Xmlhttprequest.handleError (xhr.js:83)

Unchecked Runtime.lastError: The message port closed before a Response was revived.

Devtools failed to load Sourcemap: Could not load content for Chrome-Extension://gighmmpiobklfepjocnamgkkbiglidom/include.preload.js.map: HTTP error: status code 404, net::ERR_UNKNOWN_URL_SCHEME

Devtools failed to load Sourcemap: Could not load content for Chrome-Extension://gighmmpiobklfepjocnamgkkbiglidom/include.postload.js.map: HTTP error: status code 404, net:ERR_UNKNOWN_URL_SCHEME

In Firefox:

Erro exibido no console do navegador

I don’t know what to do and how to fix it.

2 answers

1

You have a rejection of CORS.

Check the request and response headers and see if your server. The header Access-Control-Allow-Origin is very important when it comes to script requests, as MDN says:

For security reasons, browsers restrict scripted HTTP cross-origin requests.

Ensure that it is set correctly

In the cases I went through, what else was happening was:

  • The lack of the header Access-Control-Allow-Origin or its proper use.
  • The requisition was as Accept-Language values the server did not accept
  • The method of requisition options was not accepted by the server.

Take a look at this MDN material, it is essential to understand what CORS is and why it exists

0

The componentDidMount does not need to be asynchronous, so try:

componentDidMount() {
 api.swAPI("films", "get", (response) => {
  this.setState({ filmes: response.data });
 });
}

In the template check like this:

{filmes && filmes.length ? filmes.map((filme) => (
          <div class="card">
            <div class="card-body">
              <h2 class="card-title">{filme.results.title}</h2>
              <h3 class="card-episode">{filme.results.director}</h3>
              <h4 class="card-date">{filme.results.release_date}</h4>
              </div>
              </div>    
        )) : (null)}

In your api file try so:

import axios from 'axios';

const api = {
    swAPI(path, method, callback) {
        axios({
            url: `https://swapi.dev/api/${path}`,
            method: method,
        }).then((result) => {
            callback(result);
        });
    }
}

export default api;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.