简体   繁体   中英

How to call a Laravel Api route from ReactJS component?

I have an API developed with Laravel 5.7 linked with the client side which is developed with ReactJS.

I have a page which shows a list of restaurants, and there's a delete button behind every restaurant item.

So I want when I click this button the restaurant will be deleted, in other words the component calls the route of the Laravel API which calls the method in the controller to destroy this item.

This is my API route who calls the method of the delete.

Route::delete('/post/{id}', 'PostController@destroy'); .

And I tried this attempt but nothing changed :

class RestaurantCard extends Component {
  constructor(props) {
    super(props)
    this.state = {
      redirect: false,
    }
  }

  deleteRestaurant(restaurantId) {
    fetch('http://myAPI.com/version/public/post/' + restaurantId, {
      method: 'DELETE',
      header: {
        'Accept': 'application/json',
        'content-Type': 'application/json'
      }
    });

  }
render ()
 {
//...
<button onClick={() => this.deleteRestaurant(this.props.id)}>Delete</button>
}
}

Finally when I open the console it shows me those errors :

DELETE http://myapi.com/version/public/post/2146 500 (Internal Server Error).

Access to fetch at ' http://myapi.com/v003/public/post/2146 ' from origin ' http://localhost:3000 ' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

Uncaught (in promise) TypeError: Failed to fetch.

PS: I'm a beginner in ReactJs Framework !

After your edited question providing the error, this answer is invalid. Your error is due to CORS.

You need to use the then clause to provide an action when succeed. Otherwise you can also use async/await to wait for the response. More info: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch .

Add following lines to bootstrap/app.php:

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: *');
header('Access-Control-Allow-Headers: *');

Error 500 mean you have an error into your laravel class PostController->destroy method. You can display error on browser console in development tools

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