Laravel 11:即使在 config/cors.php 文件设置之后也存在 CORS 问题

问题描述 投票:0回答:1

在 Laravel/React vite 项目上工作,我面临 CORS 问题,通过查看 laravel 文档,它说在配置目录中生成一个简单的 cors.php 将解决该问题,但我仍然面临这个问题我的前端,

请注意,我尝试了fruitcake/其他包cors php解决方案,但由于依赖冲突而无法安装它。

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Cross-Origin Resource Sharing (CORS) Configuration
    |--------------------------------------------------------------------------
    |
    | Here you may configure your settings for cross-origin resource sharing
    | or "CORS". This determines what cross-origin operations may execute
    | in web browsers. You are free to adjust these settings as needed.
    |
    | To learn more: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
    |
    */

    'paths' => ['*', 'sanctum/csrf-cookie'],

    'allowed_methods' => ['*'],

    'allowed_origins' => ['*'],

    'allowed_origins_patterns' => [],

    'allowed_headers' => ['*'],

    'exposed_headers' => false,

    'max_age' => 0,

    'supports_credentials' => true,

];

在前端使用 axios 的简单 HTTP 请求

    useEffect(() => {
        const getReportList = async () => {
            try {
                setIsLoading(true);
                const response = await API.get('admin/reports');
                setReports(response.data.data);
                setFilteredReports(response.data.data);
                setActiveReport(response.data.data[0]);
            } catch (error) {
                errorManager(error);
            } finally {
                setIsLoading(false);
            }
        }
        getReportList();
    }, [])

我的 API axios 实例片段

import axios from "axios";
import {
    SERVER_URL
} from "../../constants";

const API = axios.create({
    baseURL: SERVER_URL[
        import.meta.env.VITE_ENVIRONMENT],
    timeout: 12000,
    withCredentials: true
});

API.interceptors.request.use(async (config) => {
    return config;  //to handle later
});

API.interceptors.response.use(
    function (response) {
        return response;  //to handle later
    },
    function (error) {
        return error; //to handle later
    }
);

export default API;

CORS issue in frontend

php laravel axios cors vite
1个回答
0
投票

这可能听起来很奇怪,但基本上我只是硬刷新页面并从后端删除 config/cors.php 并重新执行命令

php artisan config:publish cors

一切都很好!

© www.soinside.com 2019 - 2024. All rights reserved.