Using API no React JS

I'm new to ReactJS and I'm learning about API. I'm trying to use a Star Wars API, but it's not giving me back. I've used others and they worked.

This is my app file.js:

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 file.js

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 error 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 at createError (createError.js: 16) at XMLHttpRequest.handleError (xhr.js: 83)

Unchecked runtime.lastError: the message port closed before a response was received.

DevTools failed to load SourceMap: Could not load content for chrome-extension: / / gighmpiobklfepjocnamgkkbiglidom / 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: / / gighmpiobklfepjocnamgkkbiglidom / include.postload.js.map: HTTP error: status code 404, net:: ERR_UNKNOWN_URL_SCHEME

No Firefox:

Error displayed in browser console

I don't know what to do and how to do to fix this.

Author: Rafael Tavares, 2020-06-11

2 answers

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 scripted requests, as MDN says:

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

Ensure that it is set correctly

In the cases where I went through this, what else occurred was:

  • the lack of header Access-Control-Allow-Origin or its correct use.
  • the request had as Accept-Language values that the server did not accept
  • the request method 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

 1
Author: Luan Vinicius, 2020-11-06 02:20:21

ComponentDidMount does not need to be asynchronous, try this:

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 this:

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;
 0
Author: loabrantes, 2020-06-22 23:21:14