在本地做测试的时候,使用localhost访问接口出现如下提示:
Access to XMLHttpRequest at 'http://wxmini.test.com/api/win_lottery/addLottery' from origin 'http://localhost:8080' has been blocked by CORS policy: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.
很明显就是服务端不允许当前host访问,简而言之就是跨域了.
解决跨域问题,可以在服务端设置header允许,也可以用 jsonp ,这里直接服务端处理了。
<?php
/**
* 将请求域名加入到允许header中
*/
namespace app\common\behavior;
use think\Exception;
use think\Response;
class CronRun
{
public function run(&$dispatch){
$origin = isset($_SERVER['HTTP_ORIGIN'])? $_SERVER['HTTP_ORIGIN'] : '';
if($origin == '') {
if (isset($_SERVER['HTTP_REFERER']) && $_SERVER['HTTP_REFERER'] != "") {
$url_arr = parse_url($_SERVER['HTTP_REFERER']);
if (is_array($url_arr)) {
$origin = $url_arr['scheme'].$url_arr['host'];
}
}
}
$allow_origin = array(
// 根据需要填写允许列表, 如果传 * 则标识允许全部域名访问[不推荐]
"http://localhost:8080"
);
if (in_array($origin, $allow_origin)) {
$headers = [
"Access-Control-Allow-Origin" => $origin,
"Access-Control-Allow-Credentials" => 'true',
"Access-Control-Allow-Headers" => "x-token,x-uid,x-token-check,x-requested-with,content-type,Host"
];
if($dispatch instanceof Response) {
$dispatch->header($headers);
} else if($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
$dispatch['type'] = 'response';
$response = new Response('', 200, $headers);
$dispatch['response'] = $response;
}
}
}
}
编写了行为类,使用时直接注入到 使用的标签处。
EXP : application/tags.php
app_begin => [
'app\\common\\behavior\\CronRun'
]
根据需要修改 $allow_origin
423




被折叠的 条评论
为什么被折叠?



