ReactJS запити до сервера

Запити до сервера через axios

Установка командою yarn add axios

Простий GET запит

import axios from 'axios'

// у метод componentDidMount додаємо

axios.get('https://reactjs-quiz-c86fb.firebaseio.com/quiz.json').then(response => {
            console.log(response)
})

// або

async componentDidMount() {
        try{
            const response = await axios.get('https://reactjs-quiz-c86fb.firebaseio.com/quizes.json')

            const quizes = []

            Object.keys(response.data).forEach((key, index) => {
                quizes.push({
                    id: key,
                    name: `Тест №${index+1}`
                })
            })

            this.setState({
                quizes
            })
        } catch (e) {console.log(e)}
    } 

Надсилання даних на сервер

axios.post(
            'https://reactjs-quiz-c86fb.firebaseio.com/quizes.json',
            this.state.quiz
        ).then(
            response => {
                console.log(response)
            }
        ).catch(
            error => console.log(error)
        )

або

try {
            const response = await axios.post('https://reactjs-quiz-c86fb.firebaseio.com/quizes.json', this.state.quiz)
            console.log(response.data)
        } catch (error) {console.log(error)} 
2015-2026 © SumyNikNet