Bolboa Bolboa - 29 days ago 7
React JSX Question

how to make a restAPI call to laravel using react

Currently, my

restAPI
and my App are both hosted on
XAMPP
. My
restAPI
url is
laravel.dev
.

My
POST
route looks as so...

Route::post('/content', 'Test@save');


and my Controller...

class Test extends Controller
{
public function save()
{
return "here";
}
}


Pretty simple, but now I want to make a
POST
request to this route from my App. I am trying to that using react's
fetch
, but I do not know what URL to put since my attempt does not work...

fetch('laravel.dev', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
firstParam: 'yourValue',
secondParam: 'yourOtherValue',
})
})
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson);
});


I don't care about passing anything to the route, I just want a successful call to the
restAPI
server. Right now I'm getting...

POST http://localhost/App/src/laravel.dev 404 (Not Found)


That is also the wrong path as well, as
/App
is my app and I am trying to call the
restAPI
server.

What do I need to change to make a successful call?

Answer

fetch needs a protocol. Right now it tries to request a "local" resource. Also, add your endpoint:

fetch('http://laravel.dev/content', {
  // ...
});