我有一个进行 API 调用的 Angular 服务。这是我的subscribe.service.ts
文件
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http'
@Injectable({
providedIn: 'root'
})
export class SubscribeService {
readonly postURL = "http://localhost/sampleproject/frontend/web/api/subscribe";
constructor(private http:HttpClient) { }
subscribeSubmit(subscriber){
return this.http.post(this.postURL, subscriber);
}
}
被称为 API 的 postURL 在 yii2 中。下面是我的ApiController.php
文件
<?php
namespace frontend\controllers;
use Yii;
use yii\web\Controller;
class ApiController extends Controller {
public $enableCsrfValidation = false;
public static function allowedDomains() {
return [
'*',
];
}
public function behaviors() {
return array_merge(parent::behaviors(), [
'corsFilter' => [
'class' => \yii\filters\Cors::className(),
'cors' => [
'Origin' => static::allowedDomains(),
'Access-Control-Request-Method' => ['POST'],
'Access-Control-Allow-Credentials' => true,
'Access-Control-Max-Age' => 3600,
],
],
]);
}
public function beforeAction($action) {
if (\Yii::$app->getUser()->isGuest &&
\Yii::$app->getRequest()->url !== \yii\helpers\Url::to(\Yii::$app->getUser()->loginUrl) && Yii::$app->controller->action->id != 'subscribeforangular') {
\Yii::$app->getResponse()->redirect(Yii::$app->request->BaseUrl . '/../../login');
}
else {
return parent::beforeAction($action);
}
}
public function actionSubscribe(){
print_r($_POST);
}
}
我正在尝试使用 http.post 从角度发布数据到 yii2 中的操作"subscribe"
,但我收到以下错误
Access to XMLHttpRequest at 'http://localhost/sampleproject/frontend/web/api/subscribe' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
当我在控制台中签入“网络”时,没有添加以下行,这表示我在控制器中编写的内容没有实现 CORS。根据我的研发,必须在“ http://localhost/sampleproject/frontend/web/api/subscribe ”中添加以下行
HTTP/1.1 200 OK
Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: https://my-site.example.com
Content-Type: application/json; charset=UTF-8
Date: Fri, 24 Feb 2017 09:21:47 GMT
Server: Apache
Content-Length: 27
Connection: keep-alive
我已经搜索了解决方案并实施了它们,但在所有情况下我仍然遇到相同的错误。
请帮忙 !!我从 2 天开始就在尝试这个。我无法找到合适的解决方案,因此在此处发布。