0

How to give axios my Token to use it for the GET operation not only for PUT or POST. I am using ReactJs with Redux.

This is the vertion used: "axios": "^0.19.2" "react-redux": "^7.2.0"

Here is the code that is working, but I want to restrict security and in backend in django the permition_class is = permission_classes = (permissions.IsAuthenticated, ).

When this one is activated I get this error:

createError.js:16 Uncaught (in promise) Error: Request failed with status code 401

import React from "react";
import axios from "axios";
import TableData from "../../componentes/TableData";
import CustomForm from "../../componentes/FormCliente";
import Modal from "../../componentes/Modal";

class ClienteList extends React.Component {
  state = {
    articles: []
  };

  fetchArticles = () => {
    axios.get("http://192.168.196.49:8000/clientes/api/").then(res => {
      this.setState({
        articles: res.data

      });
    });
  }

  componentDidMount() {
    this.fetchArticles();
   }

  componentWillReceiveProps(newProps) {
    if (newProps.token) {
      this.fetchArticles();      
    }
  }

  render() {

    const dummy = event => {
      console.log('mostrando dummy:', event.target.id);
    }

    //console.log("DEBUG_ClientesListView_noFOR:", this.state.articles )

    const encabezado = [

        {
          label: 'Cliente',
          field: 'nombre',
          sort: 'asc',
          width: 150
        },
        {
          label: 'Fecha de alta',
          field: 'fecha_alta',
          sort: 'asc',
          width: 270
        },
        {
          label: 'Herramientas',
          field: 'id',
          sort: 'asc',
          width: 270
        }

      ];

    return (
      <div>
        <TableData data={this.state.articles} Encabezado={encabezado}/> <br />
        <h2> Create an article </h2>
        <CustomForm requestType="post" articleID={null} btnText="Create" />
        <Modal />
        <button id="dummy" onClick={dummy}>Dummy button</button>

      </div>
    );
  }
}

export default ClienteList;
Kentron.dna
  • 183
  • 11
  • 1
    Does this answer your question? [Sending the bearer token with axios](https://stackoverflow.com/questions/40988238/sending-the-bearer-token-with-axios) – Paolo Mar 28 '20 at 19:42
  • How to ctach the Token that is stored some where so i can use it? – Kentron.dna Mar 28 '20 at 19:50

1 Answers1

0

I found a solution. with connect you can access to the Redus store and retrive your Token.

Here is the code:

import React from "react";
import axios from "axios";
import TableData from "../../componentes/TableData";
import CustomForm from "../../componentes/FormCliente";
import Modal from "../../componentes/Modal";
//Función que conecta un componente a Redux store.
import { connect } from "react-redux";

class ClienteList extends React.Component {
  state = {
    articles: []
  };

  fetchArticles = () => {
    axios.defaults.xsrfHeaderName = "X-CSRFTOKEN";
    axios.defaults.xsrfCookieName = "csrftoken";
    axios.defaults.headers = {
      "Content-Type": "application/json",
      Authorization: `Token ${this.props.token}`,
    };
    axios.get("http://192.168.196.49:8000/clientes/api/").then(res => {
      this.setState({
        articles: res.data
      });
    });
  }

  componentDidMount() {
    this.fetchArticles();
   }

  componentWillReceiveProps(newProps) {
    if (newProps.token) {
      this.fetchArticles();      
    }
  }

   render() {
    console.log("Token_desde_connect:", this.props.token);


    const dummy = event => {
      console.log('mostrando dummy:', event.target.id);
    }


      const encabezado = [

        {
          label: 'Cliente',
          field: 'nombre',
          sort: 'asc',
          width: 150
        },
        {
          label: 'Fecha de alta',
          field: 'fecha_alta',
          sort: 'asc',
          width: 270
        },
        {
          label: 'Herramientas',
          field: 'id',
          sort: 'asc',
          width: 270
        }

      ];

    return (
      <div>
        <TableData data={this.state.articles} Encabezado={encabezado}/> <br />
        <h2> Create an article </h2>
        <CustomForm requestType="post" articleID={null} btnText="Create" />
        <Modal />
        <button id="dummy" onClick={dummy}>Dummy button</button>

      </div>
    );
  }
}

const mapStateToProps = state => {
  return {
    token: state.token
  };
};

export default connect(mapStateToProps)(ClienteList);
Kentron.dna
  • 183
  • 11