報(bào)錯(cuò)信息: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)有頁(yè)面發(fā)起連接時(shí),將對(duì)應(yīng)連接的client_id發(fā)給網(wǎng)站頁(yè)面這一步驟的時(shí)候,發(fā)起ajax請(qǐng)求之后出現(xiàn)跨域問(wèn)題,
前端頁(yè)面請(qǐng)求:
$.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。關(guān)于GatewayClient參見(jiàn)本頁(yè)面底部介紹
require_once 'E:\phpstudy\phpstudy_pro\WWW\fgw\public\static\GatewayClient-master\Gateway.php';
// GatewayClient 3.0.0版本開(kāi)始要使用命名空間
use GatewayClient\Gateway;
use think\Request;
// 設(shè)置GatewayWorker服務(wù)的Register服務(wù)ip和端口,請(qǐng)根據(jù)實(shí)際情況改成實(shí)際值(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';
// 假設(shè)用戶(hù)已經(jīng)登錄,用戶(hù)uid和群組id在session中
$uid= 1;
$group_id = 1;
// client_id與uid綁定
Gateway::bindUid($client_id, $uid);
// 加入某個(gè)群組(可調(diào)用多次加入多個(gè)群組)
Gateway::joinGroup($client_id, $group_id);
echo json_encode(array('state'=>'success'));
}
}
求大神求教
跨域也是訪(fǎng)問(wèn)你tp5的跨域,服務(wù)端與服務(wù)端是沒(méi)有跨域的.
這是我以前tp5處理跨域的,注意,這個(gè)是根據(jù)請(qǐng)求地址,動(dòng)態(tài)設(shè)置允許跨域的域名,所以是允許所有網(wǎng)站訪(fǎng)問(wèn)的.
//請(qǐng)求頭的 Origin 值
$web = request()->header('Origin');
//跨域請(qǐng)求設(shè)置
header("Access-Control-Request-Method:GET,POST");
header("Access-Control-Allow-Credentials:true");
header("Access-Control-Allow-Origin:".$web);
if (request()->isOptions()) {
exit;
}