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

Laravel API强制返回JSON响应求助:无正确请求头错误返回HTML

Hey, I've run into this exact issue before when building Laravel APIs—super frustrating when you expect JSON but get a full HTML error page, right? Let me walk you through a few solid solutions, including refining the middleware idea you already have:

1. Fix the Root Cause: Ensure Laravel Recognizes API Requests

Laravel’s default error response behavior depends on whether it identifies the request as an API call. The simplest fix is to either:

  • Enforce clients to send the Accept: application/json header (this is RESTful API best practice)
  • Or, force API routes to always return JSON responses, even if the client forgets the header.

Here’s how to implement the latter with a middleware (cleaner than manually inserting headers blindly):

<?php

namespace App\Http\Middleware;

use Closure;

class ForceJsonResponse
{
    public function handle($request, Closure $next)
    {
        // Only apply to API routes
        if ($request->is('api/*')) {
            $request->headers->set('Accept', 'application/json');
        }

        return $next($request);
    }
}

Don’t forget to register this middleware in app/Http/Kernel.php—add it to the $middlewareGroups['api'] array so it runs automatically for all API routes.

2. Customize Exception Handling for Consistent JSON Responses

Even with the middleware, it’s wise to override Laravel’s exception handler to guarantee JSON output for API errors. Open app/Exceptions/Handler.php and update the render method:

public function render($request, Throwable $exception)
{
    // Check if this is an API request (via route pattern or request header)
    if ($request->is('api/*') || $request->wantsJson()) {
        $statusCode = method_exists($exception, 'getStatusCode') 
            ? $exception->getStatusCode() 
            : 500;

        // Build a structured JSON error response
        return response()->json([
            'error' => [
                'message' => $exception->getMessage() ?: 'An unexpected error occurred',
                'code' => $statusCode
            ]
        ], $statusCode);
    }

    // Fallback to default HTML response for non-API requests
    return parent::render($request, $exception);
}

This will catch all exceptions (including authorization failures and findOrFail()’s ModelNotFoundException) and convert them to JSON for API routes.

3. Bonus: Handle Specific Exceptions Gracefully

For more control, you can catch specific exceptions in the handler to return tailored messages. For example, handle ModelNotFoundException (thrown by findOrFail()) like this:

use Illuminate\Database\Eloquent\ModelNotFoundException;

// Inside the render method, before the general API check
if ($exception instanceof ModelNotFoundException) {
    if ($request->is('api/*')) {
        return response()->json([
            'error' => 'Resource not found'
        ], 404);
    }
}

Quick Tips

  • Always test edge cases: send requests without the Accept header, trigger authorization failures, and verify you get JSON every time.
  • If you’re using Laravel’s built-in auth middleware (like auth:api), make sure it’s applied to your API routes to handle authorization consistently.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:14:40