Level 50
Add an "Accept": "application/json" header to your API requests. That way Laravel knows to send JSON responses instead of HTML.
my controller
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Http\Requests\Api\AuthenticationRequest;
use App\Models\User;
use Illuminate\Http\Request;
class AuthenticationController extends Controller
{
public function store(AuthenticationRequest $request)
{
$attributes = [
'name' => $request->name,
'email' => $request->email,
'password' => $request->password,
];
$user = User::create($attributes);
session()->flash('success', 'Account registered successful.');
return response()->json([
'message' => 'User created successfully',
'user' => $user
], 201);
}
}
my react form submission
function handleSubmit(e) {
e.preventDefault();
fetch("http://127.0.0.1:8000/api/register", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(form),
})
.then((response) => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
})
.then((data) => {
console.log("Success:", data);
setSuccess(data.message);
})
.catch((error) => {
console.error("Error during registration:", error);
setError("Registration failed. Please try again.");
});
}
getting this error in console when submitting the form
Register.jsx:25 Fetch finished loading: POST "http://127.0.0.1:8000/api/register".
Register.jsx:43 Error during registration: SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON
Register.jsx:25 Fetch finished loading: GET "http://localhost:3000/".
What's I'm missing?
Add an "Accept": "application/json" header to your API requests. That way Laravel knows to send JSON responses instead of HTML.
Please or to participate in this conversation.