从 React 应用程序调用 laravel api 时出现 CORS 问题

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

我有一个 laravel(8.12) 后端应用程序在 Xampp 上运行,使用 PHP(8),网址为 http://localhost/testbe

我的前端正在 http://localhost:3000 上运行

我的前端正在通过 axios 获取 api。

axios配置

const api = axios.create({
  headers: {
    "Content-Type": "application/json",
   },
  withCredentials: true,
});

API 给出以下错误:

Access to XMLHttpRequest at 'http://localhost/testbe/api/v1/admin/roles' from origin 'http://localhost:3000' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

./config/cors.php

<?php

return [

    'paths' => ['api/*', 'sanctum/csrf-cookie'],
    'allowed_methods' => ['*'],
    'allowed_origins' => ['http://localhost:3000'],
    'allowed_origins_patterns' => [],
    'allowed_headers' => ['*'],
    'exposed_headers' => [],
    'max_age' => 0,
    'supports_credentials' => false,

];

./app/http/kernel.php

<?php

protected $middleware = [
        // \App\Http\Middleware\TrustHosts::class,
        \Fruitcake\Cors\HandleCors::class,
        \App\Http\Middleware\TrustProxies::class,
        \App\Http\Middleware\PreventRequestsDuringMaintenance::class,
        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
        \App\Http\Middleware\TrimStrings::class,
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
    ];


./
php laravel cors xampp laravel-8
1个回答
0
投票

错误

从源“http://localhost:3000”访问“http://localhost/testbe/api/v1/admin/roles”处的 XMLHttpRequest 已被 CORS 策略阻止:“Access-Control-Allow”的值当请求的凭据模式为“include”时,响应中的“-Origin”标头不得为通配符“*”。 XMLHttpRequest 发起的请求的凭证模式由 withCredentials 属性控制。

表示目标站点的

Access-Control-Allow-Origin
响应标头具有通配符值
*
,该值与
include
作为请求的凭证模式不兼容。为了实现此目的,您需要将请求更改为
withCredentials
为 false,或者您可以明确指定您所定位的网站的来源(前提是您可以控制它)。

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