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

우선 프론트엔드는 제가 직접 작성하기 때문에 axios 구성에서 다음과 같이 설정했습니다. withCredentials: true // 크로스 도메인 시 쿠키 보내기 요청

// 创建一个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.

로 설정되어야 합니다. 즉, http://a.com이 http://b.com을 요청할 때 http:// a.com은 반드시 Origin을 http://로 설정해야 합니다. b.com은 pass할 수 있습니다Thinkphp withCredentials 교차 도메인 문제 해결 아이디어 분석

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

 $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는 <code>router.php에서 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);
    }
}
Route::group('', function (){
    ....
    这里写路由
    ....
})->middleware(['CrossDomain']);

을 생각했는데 새로운 문제가 발생했습니다 axios配置中, 我设置了如下

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

....
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 时, origin 是不允许为 *的, origin必须设置为来源的地址

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

最后参阅配置如下

rrreee

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

rrreee

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

rrreee

router.php

rrreee

然后又有一个新问题

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

위가 라우팅 파일이기 때문에, 요청된 url이 경로와 일치하면 교차 도메인 미들웨어로 이동합니다. 모두가 알고 있듯이 delete 및 put과 같은 메서드는 옵션 요청을 미리 시작합니다. 즉, 라우팅 파일을 일치시킬 수 없으며 크로스 도메인 미들웨어는 사용할 수 없습니다

So:

오류 예외 인수 정의 https://www.kancloud.cn/manual/thinkphp5_1/354092#_42

rrreee
완료. 🎜🎜

위 내용은 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 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

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

SecList

SecList

SecLists는 최고의 보안 테스터의 동반자입니다. 보안 평가 시 자주 사용되는 다양한 유형의 목록을 한 곳에 모아 놓은 것입니다. SecLists는 보안 테스터에게 필요할 수 있는 모든 목록을 편리하게 제공하여 보안 테스트를 더욱 효율적이고 생산적으로 만드는 데 도움이 됩니다. 목록 유형에는 사용자 이름, 비밀번호, URL, 퍼징 페이로드, 민감한 데이터 패턴, 웹 셸 등이 포함됩니다. 테스터는 이 저장소를 새로운 테스트 시스템으로 간단히 가져올 수 있으며 필요한 모든 유형의 목록에 액세스할 수 있습니다.

PhpStorm 맥 버전

PhpStorm 맥 버전

최신(2018.2.1) 전문 PHP 통합 개발 도구

Atom Editor Mac 버전 다운로드

Atom Editor Mac 버전 다운로드

가장 인기 있는 오픈 소스 편집기

ZendStudio 13.5.1 맥

ZendStudio 13.5.1 맥

강력한 PHP 통합 개발 환경