CORS 跨域问题
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class Cors
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle(Request $request, Closure $next)
{
// 设置允许访问的域地址
$domains = ['http://localhost:8080','http://127.0.0.1:8080'];
// 判断请求头中是否包含ORIGIN字段
if(isset($request->server()['HTTP_ORIGIN'])){
$origin = $request->server()['HTTP_ORIGIN'];
if (in_array($origin, $domains)) {
//设置响应头信息
header('Access-Control-Allow-Origin: '.$origin);
header('Access-Control-Allow-Headers: Origin, Content-Type, Authorization');
// echo "aaa";die;
}
}
return $next($request);
}
}
注册了这个中间件
跨域请求的时候报
Access to XMLHttpRequest at 'http://blog.com/api/getArticleList' from origin 'http://localhost:8080' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header contains multiple values 'http://localhost:8080, *', but only one is allowed.
但是如果在设置header(‘Access-Control-Allow-Origin: ‘.$origin);header(‘Access-Control-Allow-Headers: Origin, Content-Type, Authorization’);
echo “aaa”;die;掉却可以获取得到,
config: {url: "http://blog.com/api/getArticleList", method: "get", headers: {…}, transformRequest: Array(1), transformResponse: Array(1), …}
data: "aaa"
headers: {content-type: "text/html; charset=UTF-8"}
request: XMLHttpRequest {readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, onreadystatechange: ƒ, …}
status: 200
statusText: "OK"
请问一下这是什么原因造成的。还是我哪里写错了
设置响应头