How to deal with the REST API requests React

REST API is typically used for Web development. They are Web applications to each other "talk" to the programming interface. They are used to access functions and data members. "REST" (Representational State Transfer) API is a concept defined attributes. This article will focus on how to use a Web-based API to retrieve data from the database.

Axios npm is a software package that allows an application sends an HTTP request to the Web API. To use Axios React in your application, use the following command:

npm install axios

Or

yarn add axios

Before you create react components, React and Axios please import the file by following these steps:

import React from 'react';
import axios from 'axios';

React utilizes Axios request lifecycle methods 'componentWillMount' in. Although this method has since been outdated, but can still be used at the time of writing. It will continue until React 17 release. When you need asynchronous rendering, it is not safe to use. It should be used "componentDidMount" method instead.

After running the method component updates to DOM, it is a good place to registered API call. The basic structure so far is as follows:

class YourComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      posts: []
    }
  }
  componentDidMount() {
    // Your axios request here
  }

  render() {
    return (
    //  Your jsx goes here
    );
  }
}

Axios request has the following basic structure:

axios({ method: 'http request method', url: 'Api url' });

As indicated above, the basic request object as a parameter. In this object, specify the method and the URL of the key. The method of HTTP request and the type of API URL are set to their respective values.

GET request

In consideration of this basic model, Axios GET request as follows:

const apiUrl = '你的api地址';

axios({ method: 'get', url: `${apiUrl}` });

When the API receives a request and processes the request, it will send a response. The assembly needs to process the received data in some way, then it can be used in the application. In this example, we define a key named "posts" in the state, and set an empty array. Axios request is asynchronous. We need the "then" linked to the end of the request to process the response.

Then in a block, we can update the following components:

axios({ method: 'get', url: `${apiUrl}` })
  .then(response => {
    this.setState({
      posts: response.data
    })
  });

(The PS. If we redux for state management, may be in the 'then' block called scheduling function. Thus, we can in response to data stored in the storage redux).

POST request

For a typical POST request, the data request is passed with the API. The data is typically in a state of the component may reside Redux or storage. Typically, users want to publish the data in the database is obtained from the form. We will use state handleChange function of the updated components. Axios our request will be issued handleSubmit function.

After submitting the form, POST request is sent to the API. You can complete the following steps:

class YourComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      post: ''
    }
  }

  handleChange(e) {
    const { value } = e.target;
    this.setState({
      post: value
    });
  }

  handleSubmit(e) {
    e.preventDefault();

    const { post } = this.state;

    axios({
      method: 'post',
      url: `${apiUrl}/posts`,
      data: post
    })
  }

  render() {
    return (
    //  Your form resides here
    );
  }
}

Delete request

DELETE request is similar to the POST request. These are the buttons to interact with the view to complete. In this case, when you click the "delete" button, you can use the function handleClick request. You can complete the following steps:

class YourComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      posts: [
        {
          id: 1,
          content: 'The first post'
        }
      ]
    }
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick(e) {
    e.preventDefault();

    const { id } = e.target;
    const apiUrl = '你的api地址';

    axios({
      method: 'delete',
      url: `${apiUrl}/posts/${id}`
    })

  }

  render() {
    const { posts } = this.state;
    return (
      <div>
        {posts.map(post => (
          <div key={post.id}>
            <p>{post.content}</p>
            <div>
              <input 
                type="button"
                id={post.id}
                value="Delete"
                onClick={this.handleClick}
              />
            </div>
          </div>
        ))}
      </div>
    );
  }
}

After clicking the button, the DELETE request to the api, and delete posts from the database. In order to reflect this at the front end, another GET request must send a state update component.

JWT's request

JWT (JSON Web token) can be used for Web-based application to authenticate users. These tokens are typically sent by a POST request to the API to generate a properly configured. After the token generation, they are stored by localStorage to use. In this case, the token will need to form part of the HTTP request issued.

To illustrate this point, we will review the GET request example:

const apiUrl = '你的api地址';
const token = `Bearer ${localStorage.getItem('jwt')}`;

axios({
  method: 'get',
  url: `${apiUrl}`,
  headers: { Authorization: token }
});

As the key token passed to another object parameters passed in the call Axios. POST, and DELETE request can be changed in a similar manner, and the "header" key token transfer.

There. This is a front-end component React Axios request is very simple to understand.

Reference:
https://www.objectx.cn/thread-75-1-1.html

Guess you like

Origin blog.51cto.com/14763751/2481449