T
T
timonck2019-06-20 14:01:32
RESTful API
timonck, 2019-06-20 14:01:32

How to correctly put the received token in a GET request?

The token is written to the state, but for some reason it is not substituted into get.
What is the correct way to complete this task?
What can be read on this topic?
I will be grateful for any answer

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:"[email protected]",
                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;

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2019-06-20
@timonck

Everything should work.
1. Remove the method
2. Authorization parameter, it makes sense to write it in the default headers:

axios.defaults.headers.common.Authorization = `Bearer ${token}`;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question