I'm learning to build React JS WebApp with Laravel Back End. I have problem when try to insert data, it seems my insert function in controller is not being called whatever method I try. Here is the code;
The JS:
fetch( '/api/links/', {
method:'post',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(link)
})
.then(response => {
return response.json();
})
.then(data => {
//update the state of links
});
The /routes/api.php:
Route::post('links', 'LinksController@store');
The /app/Http/Controllers/LinksController.php:
public function store(Request $request)
{
$link = new Link;
$link->title = 'Hard Coded Just For Testing';
$link->url = 'http://but.still/not-inserted-to-database/';
$link->save();
return response()->json(null, 200);
}
My expectation there should be a new record in my Links table, but nothing new inserted.
What did I Miss?? Please Help.
UPDATE: Event though I set the method to post in fetch options, it turns out when I observe in Developer tools - network tabs, it strangely change to GET method, that's why it never get to call my store function to insert data. Does anyone know what causes this?
SOLVED: It turns out that because of extra '/' at the end of fetch URL, while in routes/api.php the URL does not have '/' at the end of it, that causing a reroute when original call to /api/links/ with POST rerouted to /api/links with GET. SO simply match the URL perfectly from the route and from the fetch, solve the problem.