简体   繁体   中英

ReactJs - My POST request is always empty

I'm trying to send a POST request using axios with ReactJS, my POST request will submit when I hit the button, but the data from the textbox is not present. Hoping somebody could point out what I've done wrong. I think I might be going wrong with the state setting.

import React, { Component } from "react";
import axios from "axios";


class SearchBar extends Component {
  state = {
    search: '',
  };

  handleChange = event =>{
    this.setState({ search: event.target.value});
  }
  
  handleSubmit = event => {
    event.preventDefault();
    const data = {
      search: this.state.search
    }
    axios
      .post("http://127.0.0.1:8080/find", {data}) 
      .then(response=>{
        console.log(response);
        this.setState({ data: response.data });
      })
      .catch((error) => {
        console.log(error);
      });
  };

  render() {
    return (
      <div className="post">
        <form className="post" onSubmit={this.handleSubmit}>
          <input
            placeholder="Search for music 'Artist - Track'"
            type="text" name="name" onChange={this.handleChange}/>
          <button type="submit">Search</button>
        </form>
                
        <div>
        {this.state.data}
        </div>
      </div>
    );
  }
}

export default SearchBar;

data is already an object you defined and you wrapped it in another object. So to get your response you will have to do response.data.data

To fix this all you need to do is remove the braces around data in your axios call

axios
    .post("http://127.0.0.1:8080/find", data) //removed braces around data
    .then(response=>{
        console.log(response);
        this.setState({ data: response.data });
    })
    .catch((error) => {
        console.log(error);
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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