報錯信息:Access to XMLHttpRequest at 'http://www.tp5.com/bind/index' from origin 'http://192.168.10.168:55151' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
本人小白一枚,看文檔是 GatewayWorker發(fā)現(xiàn)有頁面發(fā)起連接時,將對應連接的client_id發(fā)給網(wǎng)站頁面這一步驟的時候,發(fā)起ajax請求之后出現(xiàn)跨域問題,
前端頁面請求:
$.ajax({
type: 'post',
url: 'http://www.tp5.com/bind/index',
data: {
client_id:data['client_id']
},
dataType: 'json',
success: function(data) {
alert(data.state);
}
})
bind.php:
<?php
namespace app\controller;
//加載GatewayClient。關于GatewayClient參見本頁面底部介紹
require_once 'E:\phpstudy\phpstudy_pro\WWW\fgw\public\static\GatewayClient-master\Gateway.php';
// GatewayClient 3.0.0版本開始要使用命名空間
use GatewayClient\Gateway;
use think\Request;
// 設置GatewayWorker服務的Register服務ip和端口,請根據(jù)實際情況改成實際值(ip不能是0.0.0.0)
class Bind extends Base
{
public function index(Request $request)
{ header("Access-Control-Allow-Origin: *");
$client_id=$request->post('client_id');
Gateway::$registerAddress = '127.0.0.1:1236';
// 假設用戶已經(jīng)登錄,用戶uid和群組id在session中
$uid= 1;
$group_id = 1;
// client_id與uid綁定
Gateway::bindUid($client_id, $uid);
// 加入某個群組(可調(diào)用多次加入多個群組)
Gateway::joinGroup($client_id, $group_id);
echo json_encode(array('state'=>'success'));
}
}
求大神求教
跨域也是訪問你tp5的跨域,服務端與服務端是沒有跨域的.
這是我以前tp5處理跨域的,注意,這個是根據(jù)請求地址,動態(tài)設置允許跨域的域名,所以是允許所有網(wǎng)站訪問的.
//請求頭的 Origin 值
$web = request()->header('Origin');
//跨域請求設置
header("Access-Control-Request-Method:GET,POST");
header("Access-Control-Allow-Credentials:true");
header("Access-Control-Allow-Origin:".$web);
if (request()->isOptions()) {
exit;
}