简体   繁体   English

ReactJs,如何向 Axios 提供我的令牌以从 API 检索数据

[英]ReactJs, How to give to Axios my Token for retriving data from API

How to give axios my Token to use it for the GET operation not only for PUT or POST.如何给 axios 我的令牌以将其用于 GET 操作,而不仅仅是用于 PUT 或 POST。 I am using ReactJs with Redux.我在 Redux 中使用 ReactJs。

This is the vertion used: "axios": "^0.19.2" "react-redux": "^7.2.0"这是使用的版本:“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, ).这是正在运行的代码,但我想限制安全性,并且在 django 的后端 permition_class 是 = 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 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;

I found a solution.我找到了解决方案。 with connect you can access to the Redus store and retrive your Token.通过 connect,您可以访问 Redus 商店并检索您的令牌。

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM