I have created a Laravel API. Using Fetch()
I am trying to submit shopify form data (custom form) on the server. Data is correctly submitting in database. API returns ID of the last inserted row as a response. When I console the response, I am getting null in the body. Here is the screenshot:
Here is the actual response from the API.
You can see that the API returns a number but fetch function is not reading that response.
Here is my code:
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
myHeaders.append("Access-Control-Allow-Origin", "*");
var requestOptions = {
method: 'POST',
headers: myHeaders,
mode: 'no-cors',
body: $("#form").serialize(),
};
var cartContents = fetch("https://www.somesite.com/api/quotes", requestOptions)
.then(function (text) {
console.log('res',text);
})
.catch((error) => {
throw error;
});
Here is the laravel API function:
public function store(Request $request)
{
parse_str($request->getContent(), $data);
$newUser = new User([
'fname' => $data['fname'],
'lname' => $data['lname'],
'email' => $data['email'],
]);
$newUser->save();
echo $newUser->id;
die();
}
Here is the code of routes/api.php
use IlluminateHttpRequest;
use IlluminateSupportFacadesRoute;
use AppHttpControllersUser;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
Route::post('quotes', [User::class, 'store']);
I don’t understand why it have such a weird behaviour. Can anyone suggest me what I am doing wrong.
Many Thanks!