【问题标题】:Get Data from Firebase (React, Axios)从 Firebase 获取数据(React、Axios)
【发布时间】:2021-02-08 17:17:33
【问题描述】:

我得到了 firebaseConfig.js

import firebase from 'firebase/app'
import 'firebase/firestore'

const firebaseConfig = {
    apiKey: "somekey",
    authDomain: "somekey",
    databaseURL: somekey",
    projectId: "somekey",
    storageBucket: "somekey",
    messagingSenderId: "somekey",
    appId: "appIdKey"
  };

  firebase.initializeApp(firebaseConfig)    
  const db = firebase.firestore()    
  const TestRef = db.collection('myDB')

  export {TestRef}

现在我得到了组件 index.js

import {ToDosRef} from './firebase'
import axios from 'axios';

const useAPI = endpoint => {
  const [data, setData] = useState([])

  useEffect(() => {
    getData();
  },[])

  const getData = async() => {
  
    const response = await axios.get(endpoint)
    
    console.log(response.data())

    setData(response.data)
  }

  return data
}

const App = () => {
  ....
  const savedTodos = useAPI(ToDosRef)
  
  return(
    <div>
    </div>
  )
}

ReactDOM.render(
    <App />,
    document.getElementById('root')
)

当我收到'Request failed with status code 404' 时,我认为我对axios.get(endpoint) 做错了什么

【问题讨论】:

  • 您请求的端点不正确
  • 你能告诉我如何以正确的方式做到这一点吗?
  • 您正在访问 getData() 中的端点,该端点在默认状态下为空。请检查
  • 你能给我看看吗?
  • 您的端点 url 应该类似于 axios.get('/user?ID=12345') .then(function (response) { console.log(response); }) .catch(function (错误) { console.log(error); });

标签: reactjs firebase react-native google-cloud-firestore axios


【解决方案1】:

您的端点网址应该类似于

axios.get('/user?ID=12345').then(function (response) { 
  console.log(response); 
}) .catch(function (error) { 
  console.log(error); 
});

【讨论】:

    【解决方案2】:

    我找到了一些博客并按照以下方式进行操作,现在正在工作:

    致firebaseConfig.js我已添加:

    const ToDosRef = axios.create({baseURL: 'https://firestore.googleapis.com/v1/projects/project_id/databases/(default)/documents'})    
    export {ToDosRef} 
    

    然后index.js:

      const getData = async() => {
    
        const fbData = await endpoint.get(`/mDocumentName`)
        .then(response => { 
             console.log(response.data);
             console.log(response.data.documents);
    
            response.data.documents.forEach(x => {
              console.log(x);
              console.log(x.fields.id);
            })
    
           })
           .catch(error => { 
               console.log(error); 
           });
      }
    

    【讨论】:

      猜你喜欢
      • 2020-06-19
      • 2021-06-14
      • 1970-01-01
      • 2018-01-31
      • 2020-07-20
      • 2022-01-04
      • 2021-07-27
      • 2020-12-05
      • 2021-05-05
      相关资源
      最近更新 更多