我正在 Yii2 Framework 上使用预构建的 API(不是 Restfull)。它使用 JSON 数据进行响应,并根据用户类型和凭证令牌接受请求。现在我必须制作一个位于不同位置(域)的应用程序,这会导致 CORS 冲突。
我的应用程序是 jQuery 并且我正在使用$.ajax
用于数据发送和接收。
如何避免这种 CORS 冲突并通过 ajax 使用 API?
Regards
UPDATE:
正如 IStranger 在他的回答中告诉我的那样,我添加了以下代码:
public function behaviors()
{
$behaviors = parent::behaviors();
$behaviors['corsFilter'] = [
'class' => \yii\filters\Cors::className(),
'cors' => [
'Origin' => "*",
'Access-Control-Request-Method' => ['POST', 'GET'],
'Access-Control-Allow-Credentials' => true,
'Access-Control-Max-Age' => 3600,
],
];
return $behaviors;
}
但我仍然收到错误。有一个beforeAction
在代码中这会是一个问题吗?
这是原始标题
Request:
Host: domain.com
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:48.0) Gecko/20100101 Firefox/48.0
Accept: */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Referer: http://localhost/main/main.html
Content-Length: 296
Origin: http://localhost
Connection: keep-alive
回复:
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Connection: Keep-Alive
Content-Length: 101
Content-Type: application/json; charset=UTF-8
Date: Thu, 22 Sep 2016 17:23:48 GMT
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Keep-Alive: timeout=5, max=100
Pragma: no-cache
Server: Apache/2.4.17 (Win64) PHP/5.6.16
Set-Cookie: PHPSESSID=ph0b322gbq65m1f3m8fp9fphc0; path=/; HttpOnly
X-Powered-By: PHP/5.6.16