Search code examples
react-nativeexpohttp-status-code-404

Request failed with status code 404 (React Native, Axios)


Good morning.

I have this API.

I'm trying to use it in my React Native project like this:

​// api.js
 import axios from "axios";
      
 const api = axios.create({
   baseURL: "https//almodovar-98fa1-default-rtdb.firebaseio.com/",  
});


  // App.js    
  import api from "./services/api";

  import Filmes from "./components/Filmes";

  export default function App() {
  
  const [filmes, setFilmes] = useState([]);
  
  useEffect(() => {
   async function loadFilmes() {
   try {
    const response = await api.get("/.json");
  
    setFilmes(response.data);
    console.log(response);
   
   } catch (e) {
    alert(e);
  }
}
loadFilmes();
}, []);

  
 return (
  <View style={styles.container}>
    <Text style={styles.textH1}>Almodovar Cult 
    Movie List</Text>
    <FlatList
      data={filmes}
      keyExtractor={(item) => item.id}
      renderItem={({ item }) => <Filmes data= 
      {item} />}
    />
   </View>
   );
 }


// Filmes/index.js
   

import React from "react";
import { View, Text } from "react-native";

const Filmes = () => {
  return (
    <View>
      <Text>...</Text>
    </View>
  );
};

export default Filmes;

But "I'm getting this error (Expo web) Error: Request failed with status code 404

I know this error means "can't be found". What am I doing wrong?

I tried

const response = await api.get("/.json");
const newArr = [];
        Object.values(response.data).map(key, (index) => {
          newArr.push(response.data[key]);
        });

setFilmes(newArr)

and it didn't work.

If I try to run this app via Expo on the android device, the error is Network Error

I already use this api here.

Thank you for your time.


Solution

  • Try change you api.js file like this

    import axios from "axios";
    
    export default function Api(type, serviceUrl, params) {
      const baseURL = "https//almodovar-98fa1-default-rtdb.firebaseio.com/";
      let url = baseURL + serviceUrl;
    
      axios.defaults.headers.common["Accept"] = "application/json";
      axios.defaults.headers.common["Content-Type"] = "application/json";
    
      switch (type) {
        case "get":
          return axios
            .get(url, { params: params })
            .then((response) => {
              return response;
            })
            .catch((error) => {
              return error;
            });
        case "post":
          return axios
            .post(url, { params: params })
            .then((response) => {
              return response;
            })
            .catch((error) => {
              return error;
            });
        default:
          break;
      }
    }
    

    and call api from App.js like this

    const response = await api("get",".json");