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

Laravel中如何处理预检请求?(Ionic v3+Laravel5.5场景)

Fixing CORS Preflight (OPTIONS) Request Issue with Ionic v3 & Laravel 5.5

Hey there, let's tackle that OPTIONS preflight request problem you're facing. The core issue here is that browsers send an OPTIONS request first for cross-origin requests with custom headers (like your Authorization header), and your current setup with auth:api middleware is blocking this because the OPTIONS request doesn't carry the Bearer token.

Here's how to fix it properly:

1. Correctly Configure Your CORS Middleware

First, make sure your CORS middleware is set up to handle OPTIONS requests and allow the necessary headers/methods. If you don't have a Cors middleware yet, create one in app/Http/Middleware/Cors.php:

<?php

namespace App\Http\Middleware;

use Closure;

class Cors
{
    public function handle($request, Closure $next)
    {
        // Allow your Ionic app's origin (replace * with your actual app domain in production)
        $response = $next($request)
            ->header('Access-Control-Allow-Origin', '*')
            ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
            ->header('Access-Control-Allow-Headers', 'Content-Type, Authorization');

        // Handle OPTIONS requests directly to avoid auth checks
        if ($request->getMethod() === "OPTIONS") {
            return response()->json(['status' => 'ok'], 200);
        }

        return $response;
    }
}

Then, add this middleware to your API middleware group in app/Http/Kernel.php:

protected $middlewareGroups = [
    'api' => [
        'throttle:60,1',
        'bindings',
        \App\Http\Middleware\Cors::class, // Add this line
    ],
];

2. Simplify Your API Route

You don't need two separate routes anymore. Now that the CORS middleware handles the OPTIONS preflight, your main route can just use the auth:api middleware normally in routes/api.php:

Route::middleware('auth:api')->get('/user', function (\Illuminate\Http\Request $request) {
    return $request->user();
});

Your Ionic code works, but adding a check for the token will prevent unnecessary requests if the user isn't authenticated:

const token = localStorage.getItem('token');
if (token) {
    const httpOptions = { 
        headers: new HttpHeaders({ 
            'Authorization': `Bearer ${token}` 
        }) 
    }; 
    this.prf = this.httpClient.get('http://localhost/blog/public/api/user', httpOptions);
} else {
    // Redirect to login or handle unauthenticated state
    console.log('No token found, please log in');
}

This setup ensures the OPTIONS preflight request gets allowed by the CORS middleware first, then the actual GET request is authenticated via auth:api.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:46:17