跨域测试

打开一个网站(注意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

image

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

namespace appdianqianmiddleware;

use Closure;
use thinkConfig;
use thinkRequest;
use thinkResponse;

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

image

uni 跨域

前端uniapp的网络请求用的是uni.request,不管是uni.request还是jq的ajax,都一样,都需要注意一点,就是请求类型不能是application/json!!

uni.request({
 url: 'http://test-tp5.io',
  data: {a:1,b:2},
  header: {
 'content-type': 'application/x-www-form-urlencoded', // 用这个!
  // 'content-type': 'application/json', 这里是反面举例,一定不要用这个!不信你试试!
  'token': 'this is token'// 看到这个token了没有,它在在第一步的第三行出现过~
  },
  method: 'POST',
  success: (res)=> {
      console.log('成功了:',res);
},
    fail: (res)=>{
        console.log('出错了:',res);
    }
});

tp6 返回json字符串与json对象是有区别的!!!

thinkphp 默认是输出 Html 输出,所以直接以html页面方式输出响应内容。如果你发起一个JSON请求的话,输出 就会自动使用JSON格式响应输出。 为了规范和清晰起见,最佳的方式是在控制器最后明确输出类型

如我们需要输出一个JSON数据给客户端(或者AJAX请求),可以使用:
return json($data);

原文地址:https://www.cnblogs.com/jigr/p/15471368.html