【问题标题】:ReactJs, How to give to Axios my Token for retriving data from APIReactJs,如何给 Axios 我的令牌以从 API 检索数据
【发布时间】:2020-07-09 08:59:46
【问题描述】:

如何给 axios 我的 Token 以将其用于 GET 操作,而不仅仅是用于 PUT 或 POST。我正在将 ReactJs 与 Redux 一起使用。

这是使用的版本: “axios”:“^0.19.2” "react-redux": "^7.2.0"

这是有效的代码,但我想限制安全性,并且在 django 的后端,permissionion_class 是 = permission_classes = (permissions.IsAuthenticated, )。

当这个被激活时,我得到这个错误:

createError.js:16 Uncaught (in promise) 错误:请求失败,状态码为 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;

【问题讨论】:

标签: javascript reactjs api axios


【解决方案1】:

我找到了解决方案。 通过连接,您可以访问 Redus 商店并检索您的令牌。

代码如下:

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

【讨论】:

    猜你喜欢
    • 2017-01-09
    • 2019-03-16
    • 1970-01-01
    • 1970-01-01
    • 2019-04-22
    • 1970-01-01
    • 2019-06-22
    • 1970-01-01
    • 2021-06-27
    相关资源
    最近更新 更多