@timonck

Как правильно поставить полученный token в GET запрос?

Токен записывается в состояние но почему то не подставляется в get.
Как правильно выполнить эту задачу?
Что можно почитать по этой теме?
Буду благодарен за любой ответ

import React from 'react';
import axios from 'axios';
import {Table} from "reactstrap";
class Newpage extends React.Component {
constructor(props){
  super(props);
  this.state={
    token: '',
    items:[]
  }
}



    componentDidMount(){
        axios.post(`https://gentle-escarpment-19443.herokuapp.com/v1/users/auth`, 
            {
                email:"user1@email.com",
                password: '!password!'
            },
           {headers: { 
                'Content-Type': 'application/json'
              }})
          .then(res => {
            this.setState({
              token: res.data.access_token
            })
          });



          axios.get("https://gentle-escarpment-19443.herokuapp.com/v1/articles", {
            method: 'GET',
            headers: { 
              'Authorization': 'Bearer ' + this.state.token }})
          .then((response)=>{
            this.setState({
              items: response.data
            })
          });
          
        }
    
      render() {

        console.log(this.state.token)
      let items = this.state.items.map((item) => {
        return(
          <tr key={item.id}>
                <td>{item.id}</td>
                <td>{item.name}</td>
                <td>{item.price}</td>
              </tr>
        )
      });


        return (

          
          <div>
           {this.state.token}
           <Table>
            <thead>
              <tr>
                <th>#</th>
                <th>Title</th>
                <th>Price</th>
                <th>Actions</th>
              </tr>
            </thead>
            <tbody>
              {items}
            </tbody>
          </Table>
          </div>
        )
      }


  }
  
  
  export default Newpage;
  • Вопрос задан
  • 204 просмотра
Решения вопроса 1
rockon404
@rockon404 Куратор тега React
Frontend Developer
Все должно работать.
1. Уберите параметр method
2. Authorization имеет смысл записывать в заголовки по-умолчанию:
axios.defaults.headers.common.Authorization = `Bearer ${token}`;
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы