简体   繁体   中英

laravel react api : request doesn't arrived

i'm using laravel api backend with react frontend .. i'm trying to post data using axios but request dose not arrived .. here is my code in frontend

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

export default class PersonList extends React.Component {
 state = {
   product_name: '',

 }

 handleChange = event => {
   this.setState({ product_name: event.target.value });

 }

 handleSubmit = event => {
   event.preventDefault();

   const user = {
     product_name: this.state.product_name,



   };

   axios.post(`http://46.185.162.125/api/add_product`, { user })
     .then(res => {
       console.log(res);
       console.log(res.data);
     })
     .catch(error => {
   console.log(error.response)
});
 }

 render() {
   return (
     <div>
       <form onSubmit={this.handleSubmit}>
         <label>
           Name:
           <input type="text" name="product_name" onChange={this.handleChange} />
         </label>

         <button type="submit">Add</button>
       </form>
     </div>
   )
 }
}

and this is the code of backend controller

public function addProduct(Request $request)
{
        $new_product = new Product;
        $new_product->name = $request->product_name;
        $new_product->save();

        return 'success';
 }

but i get 500 error (product_name column can't be null ) and this error occurred because request dose not arrived

I trying this api on postman and it worked

How can i solve it ?

Writing { user } is a shorthand for { user: user } , so just send user as your data instead:

axios.post(`http://46.185.162.125/api/add_product`, user)
  .then(res => {
    console.log(res);
  })

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