You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel中通过API实现注册的方法咨询及报错解决:遇到"仅允许带有请求头'Accept': 'application/json'的JSON请求"错误

Hey fellow developer! Let's work through this Laravel API registration issue you're hitting. That error about requiring Accept: application/json is super common when building APIs, so let's break down how to build the registration feature properly and fix that annoying error.

1. Step-by-Step API Registration Implementation

Let's start from scratch with a clean, standard registration flow for Laravel APIs:

1.1 Create a Validation Request Class

First, generate a dedicated request class to handle registration input validation:

php artisan make:request RegisterRequest

Open the generated file at app/Http/Requests/RegisterRequest.php and add your validation rules:

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class RegisterRequest extends FormRequest
{
    // Allow all users to access this registration endpoint
    public function authorize()
    {
        return true;
    }

    // Define validation rules for registration fields
    public function rules()
    {
        return [
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users',
            'password' => 'required|string|min:8|confirmed',
        ];
    }
}

1.2 Build the Registration Controller

Next, create a controller to handle the registration logic (we'll nest it in an Api/Auth namespace for organization):

php artisan make:controller Api/Auth/RegisterController

Add the registration logic to app/Http/Controllers/Api/Auth/RegisterController.php (we'll include API token generation using Laravel Sanctum, which is standard for Laravel APIs):

<?php

namespace App\Http\Controllers\Api\Auth;

use App\Http\Controllers\Controller;
use App\Http\Requests\RegisterRequest;
use App\Models\User;
use Illuminate\Support\Facades\Hash;

class RegisterController extends Controller
{
    public function __invoke(RegisterRequest $request)
    {
        // Create the new user with validated data
        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => Hash::make($request->password),
        ]);

        // Generate an API token for the new user (requires Laravel Sanctum installed)
        $token = $user->createToken('auth_token')->plainTextToken;

        // Return a JSON success response
        return response()->json([
            'message' => 'User registered successfully',
            'user' => $user,
            'access_token' => $token,
            'token_type' => 'Bearer',
        ], 201);
    }
}

Note: If you haven't installed Sanctum yet, run composer require laravel/sanctum and follow the setup steps in the Laravel docs.

1.3 Register the API Route

Open routes/api.php and add your registration route:

use App\Http\Controllers\Api\Auth\RegisterController;

// API registration endpoint
Route::post('/register', RegisterController::class);

2. Fixing the "Only json request are allowed with header 'Accept': 'application/json'" Error

This error means your API is configured to only accept JSON-formatted requests with the correct Accept header. Here's how to resolve it based on your needs:

Chances are you have a custom middleware that's enforcing JSON requests. Let's confirm and fix how you send requests:

  • When testing with tools like Postman/Insomnia:
    • Add these two headers to your request:
      • Accept: application/json
      • Content-Type: application/json
    • Send your registration data as a JSON body, not form data:
      {
          "name": "Jane Doe",
          "email": "jane@example.com",
          "password": "securepassword123",
          "password_confirmation": "securepassword123"
      }
      

If you want to ensure this middleware is set up correctly (or add it if it's missing):

  1. Generate the middleware:
    php artisan make:middleware EnsureJsonRequest
    
  2. Add the logic to app/Http/Middleware/EnsureJsonRequest.php:
    <?php
    
    namespace App\Http\Middleware;
    
    use Closure;
    use Illuminate\Http\Request;
    use Symfony\Component\HttpFoundation\Response;
    
    class EnsureJsonRequest
    {
        public function handle(Request $request, Closure $next): Response
        {
            // Check if the request accepts JSON and is formatted as JSON
            if (!$request->wantsJson() || !$request->isJson()) {
                return response()->json([
                    'error' => 'Only json request are allowed with header "Accept": "application/json"'
                ], 400);
            }
    
            return $next($request);
        }
    }
    
  3. Register the middleware in app/Http/Kernel.php under the api middleware group:
    protected $middlewareGroups = [
        'api' => [
            \App\Http\Middleware\EnsureJsonRequest::class, // Add this line
            'throttle:api',
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],
    ];
    

If you need to accept form-data requests to your API, modify the middleware to only check the Accept header (or remove the middleware entirely):

  • Update the middleware logic to remove the !$request->isJson() check:
    if (!$request->wantsJson()) {
         return response()->json([
             'error' => 'Only json request are allowed with header "Accept": "application/json"'
         ], 400);
     }
    

Or, if you don't need any enforcement at all, just remove the EnsureJsonRequest::class entry from your api middleware group in Kernel.php.


内容的提问来源于stack exchange,提问作者abu abu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 15:17:29