如何使用axios发送帖子请求

时间:2018-06-08 01:18:31

标签: axios

在这里使用向后端发送发布请求的axios,是向后端发送post请求的唯一方法还是其他任何方法都有。使用axios发送post请求有什么优缺点。为什么我们不能使用常规方法发送post请求。我们可以使用axios的其他东西是什么。是否有像axios这样的库来做同样的工作。

// AddBooks.js

import React, {Component} from 'react';
import '../styles/AddBook.css';
import '../styles/table.css'
import axios from 'axios';

class AddBooks extends Component {
    constructor(props) {
        super(props);
        this.setSelectedAuthor = this.setSelectedAuthor.bind(this);
        this.setTitle = this.setTitle.bind(this);
        this.handleClick = this.handleClick.bind(this);

        this.state = {
            authors: [],
            selectedAuthor: null,
            title: null

        }
    }

    componentDidMount() {
        let url = 'http://localhost:8083/getBook';
        let auth = [];
        fetch(url).then(response => response.json()).then((data) => {
            data.allBook.map((book) => {
                auth.push(book.author)
            })
            this.setState({
                authors: auth
            })
        })
    }

    handleClick = ()=> {

        axios({
            method: 'post',
            url: 'http://localhost:8083/createBook',
            data: {
                "name": this.state.title,
                "author": this.state.selectedAuthor
            },
            headers: {
                "Content-Type": "application/json"
            }
        }).then(function (response) {
            console.log(response);
        }).catch(function (error) {
                console.log(error);
        });
    }

    setSelectedAuthor(value) {
        this.setState({selectedAuthor: value});
    }
    setTitle(value) {
        this.setState({title: value}, ()=>{
            console.log(this.state.title)
        });
    }

    render() {
        return(
            <div className="formDiv">
                <h2>Add Books</h2>
                <label for="fname">Title</label>
                <input type="text" id="fname" name="firstname" value={this.state.title} onChange={(e) => this.setTitle(e.target.value)} placeholder="Book title"/>

                <label for="country">Author Name</label>
                <select id="country" name="country" value={this.state.selectedAuthor} onChange={(e) => this.setSelectedAuthor(e.target.value)}>
                    <option value="select author">Select Author</option>
                    {
                        this.state.authors.map((author, key) =>
                            <option key={key} value={author}>{author}</option>
                        )
                    }
                </select>
                <br/>
                <br/>
                <button onClick={this.handleClick}>Add Book</button>
            </div>
        )
    }
}

export default AddBooks;  

0 个答案:

没有答案