찾다
PHP 프레임워크ThinkPHPThinkphp withCredentials 교차 도메인 문제 해결 아이디어 공유

다음 튜토리얼 칼럼인 thinkphp에서는 Credentials 크로스 도메인 문제 해결 아이디어가 포함된 thinkphp를 소개합니다. 도움이 필요한 친구들에게 도움이 되길 바랍니다!

여기서 교차 도메인이 무엇인지 자세히 설명하지 않겠습니다. 여기서 주요 초점은 thinkphp5.1입니다. 우선 일반적인 솔루션 아이디어에 대해 이야기하겠습니다. , 프론트 엔드는 직접 작성했기 때문에 axios 구성에서 다음과 같이 설정했습니다.

withCredentials: true // 도메인 간 요청 중에 쿠키 보내기axios配置中, 我设置了如下

withCredentials: true // 跨域请求时发送cookie

// 创建一个axios
const service = axios.create({
  baseURL: URL , 
  withCredentials: true, // 跨域请求时发送cookie
  timeout: 5000 // request timeout
})

在后端的配置中,配置的是

header("Access-Control-Allow-Origin: *");

故而抛出了这样一个错误

Access to XMLHttpRequest at 'http://store.ink/admin/me?sid=lbn3mpacfb3k1mbehnk9qh8kf3' from origin 'http://vue-admin-web.ink' 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.

意思大概为 设置 withCredentialstrue 时, origin 是不允许为 *的, origin必须设置为来源的地址

也就是 http://a.com 请求 http://b.com 的时候, http://a.com 必须设置origin 为 http://b.com 才能通过

最后参阅配置如下

 $origin = $_SERVER['HTTP_ORIGIN'] ?? '*';
        header("Access-Control-Allow-Origin: $origin");
        header('Access-Control-Allow-Credentials: true');
        header('Access-Control-Allow-Headers: Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-Requested-With');
        header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE');
        header('Access-Control-Max-Age: 1728000');

当然, 为 * 的时候也可以这样

header("Access-Control-Allow-Origin: *");
        header('Access-Control-Allow-Headers: Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-Requested-With');
        header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE');
        header('Access-Control-Max-Age: 1728000');

首先 定义个中间件 php think make:middleware CrossDomain

<?php namespace app\http\middleware;

use think\Response;


class CrossDomain
{
    public function handle($request, \Closure $next)
    {
        $origin = $_SERVER[&#39;HTTP_ORIGIN&#39;] ?? &#39;*&#39;;
        header("Access-Control-Allow-Origin: $origin");
        header(&#39;Access-Control-Allow-Credentials: true&#39;);
        header(&#39;Access-Control-Allow-Headers: Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-Requested-With&#39;);
        header(&#39;Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE&#39;);
        header(&#39;Access-Control-Max-Age: 1728000&#39;);

        return $next($request);
    }
}

router.php

Route::group('', function (){
    ....
    这里写路由
    ....
})->middleware(['CrossDomain']);

然后又有一个新问题

因为如上是走的路由文件,当请求的url

....
public function render(Exception $e)
{
    # 这里来处理跨域问题 
    $origin = $_SERVER['HTTP_ORIGIN'] ?? '*';
    header("Access-Control-Allow-Origin: $origin");
    header('Access-Control-Allow-Credentials: true');
    header('Access-Control-Allow-Headers: Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-Requested-With');
    header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE');
    header('Access-Control-Max-Age: 1728000');
    $type = request()->isAjax() ? 'json' : "html";
    $response = \think\response\Json::create([], $type, 200, []);
    return $response; # response  // 在异常处理接管中,必须返回的是一个人response响应, 而不是 `throw new `抛出一个响应
}
...
백엔드 구성에서, 구성이

rrreee

이므로 이러한 오류

rrreee

가 발생했습니다. 의미는 아마도 withCredentialstrue로 설정하면 원본이 가 될 수 없다는 뜻일 것입니다. *이며, 출발지는 소스 주소

즉, http로 설정되어야 합니다. ://a.com이 http://b.com을 요청할 때 http://a.com은 출발지를 http로 설정해야 합니다. ://b.com to pass

마지막으로 다음과 같은 구성을 참고하세요

rrreee
물론 *
rrreee

미들웨어를 먼저 정의하세요 php think make :middleware CrossDomainrrreeerouter.php

rrreee

그러면 새로운 문제가 발생합니다

위와 같이 라우팅 파일을 사용하기 때문에 요청한 url이 경로와 일치하면 크로스 도메인 미들웨어가 사용됩니다. 모두가 알고 있듯이 delete 및 put과 같은 메소드는 미리 옵션 요청을 시작하므로 라우팅 파일이 일치할 수 없으며 크로스 도메인이 됩니다. 따라서 미들웨어를 사용할 수 없습니다.
🎜 https://www.kancloud.cn/manual/ thinkphp5_1/354092#_42🎜rrreee🎜complete를 인수하려면 오류 예외를 정의하세요. 🎜🎜🎜🎜🎜관련 추천: 🎜최신 10개 thinkphp 비디오 튜토리얼🎜🎜🎜🎜

위 내용은 Thinkphp withCredentials 교차 도메인 문제 해결 아이디어 공유의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명
이 기사는 segmentfault에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 Linux 새 버전

SublimeText3 Linux 새 버전

SublimeText3 Linux 최신 버전

맨티스BT

맨티스BT

Mantis는 제품 결함 추적을 돕기 위해 설계된 배포하기 쉬운 웹 기반 결함 추적 도구입니다. PHP, MySQL 및 웹 서버가 필요합니다. 데모 및 호스팅 서비스를 확인해 보세요.

Eclipse용 SAP NetWeaver 서버 어댑터

Eclipse용 SAP NetWeaver 서버 어댑터

Eclipse를 SAP NetWeaver 애플리케이션 서버와 통합합니다.