跨域测试

打开一个网站(注意http协议要一致),按F12打开开发者工具,在Console栏中输入下列代码,点击回车执行

var xhr = new XMLHttpRequest();
xhr.open("GET", "http://xxx.com/orders");
xhr.send(null);
xhr.onload = function(e) {
    var xhr = e.target;
    console.log(xhr.responseText);
}

thinkphp6 跨域

php think make:middleware dianqian@AllowCrossDomain

跨域测试

  • AllowCrossDomain.php
<?php
declare (strict_types = 1);

namespace app\dianqian\middleware;

use Closure;
use think\Config;
use think\Request;
use think\Response;

class AllowCrossDomain
{
	protected $cookieDomain;
	
	// header头配置
	protected $header = [
		'Access-Control-Allow-Credentials' => 'true',
		'Access-Control-Max-Age'           => 1800,
		'Access-Control-Allow-Methods'     => 'GET, POST, PATCH, PUT, DELETE, OPTIONS',
		'Access-Control-Allow-Headers'     => 'xxx-token,Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-CSRF-TOKEN, X-Requested-With,token',
	];
	/**
	 * AllowCrossDomain constructor.
	 * @param Config $config
	 */
	public function __construct(Config $config)
	{
		$this->cookieDomain = $config->get('cookie.domain', '');
	}
    /**
	 * 允许跨域请求
	 * @access public
	 * @param Request $request
	 * @param Closure $next
	 * @param array   $header
	 * @return Response
	 */
	public function handle($request, \Closure $next)
	{
		header('Access-Control-Allow-Origin: *');
		header('Access-Control-Max-Age: 1800');
		header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE');
		header('Access-Control-Allow-Headers: Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-CSRF-TOKEN, X-Requested-With, Token');
		if (strtoupper($request->method()) == "OPTIONS") {
			return Response::create()->send();
		}

		return $next($request);
	}
}
  • middleware.php

跨域测试

上一篇:配置 mysql 密码 提示 Access denied for user 'root'@'localhost' (using password: YES)


下一篇:Postman 最被低估的功能,自动化接口测试