2

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 !

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129

3 Answers3

0

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.

Miguel Cabrera
  • 191
  • 1
  • 6
0

Add following lines to bootstrap/app.php:

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: *');
header('Access-Control-Allow-Headers: *');
Sumit Kumar
  • 763
  • 9
  • 14
-1

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