WZY_1514 2025-05-10 11:55 采纳率: 0%
浏览 11

Vue3+laravel10框架本地嗯能访问但是通过路由映射的专线ip+端口访问,csrs报错

Vue3+laravel10框架本地嗯能访问但是通过路由映射的专线ip+端口访问,cors报错。cors.php配置了不行。
login:1 Access to XMLHttpRequest at 'http://192.168.1.188:9099/api/login' from origin 'http://222.141.*:22222' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header has a value 'http://localhost:5173' that is not equal to the supplied origin.

<?php

namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
class CorsMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle($request, Closure $next)
    {
        $allowedOrigins = [
            'https://192.168.1.188:22222',  // 公网
            'https://222.141.*:22222',      // 内网
            'http://localhost:22222',           // 开发环境
            'http://222.141.*:22222',
            'http://222.141.*:9099',
        ];
        $origin = $request->header('Origin');
        if (in_array($origin, $allowedOrigins)) {
            $response = $next($request);
            $response->headers->set('Access-Control-Allow-Origin', $origin);
            $response->headers->set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
            $response->headers->set('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Requested-With');
            $response->headers->set('Access-Control-Allow-Credentials', 'true');
            return $response;
        }
        return $next($request);
    }
}


  • 写回答

4条回答 默认 最新

  • 阿里嘎多学长 2025-05-10 11:55
    关注

    阿里嘎多学长整理AIGC生成,因移动端显示问题导致当前答案未能完全显示,请使用PC端查看更加详细的解答过程

    问题解答

    你使用 Vue3 和 Laravel 10 构建的应用程序,能够在本地访问,但是通过路由映射的专线 IP 和端口访问时,出现 CORS 报错。已经配置了 cors.php 文件,但是问题仍然存在。

    解决方案:

    1. 在 Laravel 10 中,CORS 配置已经被移到 kernel.php 文件中,可以在 kernel.php 文件中添加以下代码:
    protected $middleware = [
        // ...
        \Illuminate\Cors\Middleware\Cors::class,
    ];
    
    1. 如果上述方法不行,可以尝试使用 cors middleware 在路由中单独使用:
    Route::group(['middleware' => ['cors']], function () {
        // 路由代码
    });
    
    1. 如果你使用的是 Vue 3,需要在 Vue 项目的 main.js 文件中添加以下代码:
    import axios from 'axios';
    axios.defaults.baseURL = 'http://your-laravel-app.com'; // 或者专线 IP 和端口
    axios.defaults.withCredentials = true;
    
    1. 如果你使用的是 Laravel 10 的 Inertia.js,可以在 inertia.js 配置文件中添加以下代码:
    'inertia' => [
        // ...
        'cors' => true,
    ],
    
    1. 最后,如果以上方法都不能解决问题,可以尝试使用 curl 命令来访问 Laravel 应用程序,检查是否有其他错误。

    希望这些解决方案能够帮助你解决问题。如果你需要更多帮助,请提供更多的信息和代码。

    评论

报告相同问题?

问题事件

  • 创建了问题 5月10日