繁体   English   中英

来自'http:// localhost / api from origin'http:// localhost:8000'的XMLHttpRequest访问已被CORS策略阻止

[英]Access to XMLHttpRequest at 'http://localhost/api from origin 'http://localhost:8000' has been blocked by CORS policy

我正在尝试在后端设置一个带有简单CRUD API的角度应用程序。 我在CORS策略方面遇到了一些问题,但我找不到正确的解决方案来解决我的错误。 我正在尝试通过角形来创建用户(看护者)。

我想我的php api中有超过必要的标题。 我把它们放在.htaccess文件中:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]

Header always set Access-Control-Allow-Origin *
Header always set Access-Control-Max-Age "1000"
Header always set Access-Control-Allow-Headers "X-Requested-With, Content-Type, Origin, Authorization, Accept, Client-Security-Token, Accept-Encoding"
Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"

我在尝试请求时也可以在Chrome控制台中看到它们:

请求

正如您所看到的,我得到状态代码400:错误的请求,但它在我的OPTIONS请求中,所以在我甚至可以发布我的表单数据之前。

那么这就是我在chrome控制台中遇到的错误: 安慰 所以我认为这是问题所在:

来自origin>' http:// localhost:8000 '的' http://localhost/api_pillassist/caregiver/create.php '访问XMLHttpRequest已被CORS策略阻止:响应>预检请求未通过访问控制检查:它没有HTTP ok> status。

我还已经下载了chrome扩展,它允许'允许控制允许来源:*',但即使这样也行不通。

我将在下面提供一些代码,虽然我不确定问题在哪里。 我也尝试在Postman中发送带有表单数据的POST请求,这样可行,所以我不知道这是否有用,但无论如何我都会包含它:

这是我在角度应用中使用的组件模板:

<ng-container>
  <form #f="ngForm" (submit)="createCaregiver()">
    <div class="input-group">
      <label for="firstName" class="appear">Voornaam</label>
      <input type="text" placeholder="Voornaam" #firstName name="firstName" />
    </div>

    <div class="input-group">
      <label for="lastName" class="appear">Achternaam</label>
      <input type="text" placeholder="Achternaam" #lastName name="lastName" />
    </div>

    <div class="input-group">
      <label for="email" class="appear">E-mailadres</label>
      <input type="text" placeholder="E-mailadres" #email name="email" />
    </div>

    <div class="input-group">
      <label for="password" class="appear">Wachtwoord</label>
      <input type="password" placeholder="Wachtwoord" #password name="password" />
    </div>

    <div class="login-height"></div>

    <div class="actions">
      <button class="btn btn-blue btn-main" type="submit">
        <span>Registreer</span>
        <img src="assets/img/icons/arrow-right.svg" alt="arrow-right" class="icon">
      </button>
      <p class="smaller-link">
        Heb je al een account? Log <a class="small-link" href="/">hier</a> in.
      </p>
    </div>
  </form>
</ng-container>

这是它链接到的'createCaregiver()'函数:

export class RegisterComponent implements OnInit {
  caregiver = new Caregiver('', '', '', '');
  error: string;

  constructor(private caregiverService: CaregiverService) {}

  ngOnInit() {}

  createCaregiver() {
    this.caregiverService.create(this.caregiver).subscribe(
      (res: Caregiver[]) => {
        console.log(res);
      },
      err => ((this.error = err), console.log(err))
    );
  }
}

这是caregiverService文件:

export class CaregiverService {
  private baseUrl = 'http://localhost/api_pillassist/caregiver';
  private caregivers: Caregiver[];

  constructor(private http: HttpClient) {}

  create(caregiver: Caregiver): Observable<Caregiver[]> {
    return this.http
      .post(`${this.baseUrl}/create.php`, { data: caregiver })
      .pipe(
        map(res => {
          this.caregivers.push(res['data']);
          return this.caregivers;
        }),
        catchError(this.handleError)
      );
  }

这是在我的api中我在create.php文件中的内容:

<?php

include_once '../config/database.php';
include_once '../objects/caregiver.php';

$database = new Database();
$db = $database->getConnection();

$caregiver = new Caregiver($db);

$data = $_POST;
$data = json_encode($data);
$data = json_decode($data);

if (
    !empty($data->firstName) &&
    !empty($data->lastName) &&
    !empty($data->email) &&
    !empty($data->password)
) {
    $caregiver->firstName = $data->firstName;
    $caregiver->lastName = $data->lastName;
    $caregiver->email = $data->email;
    $caregiver->password = $data->password;
    $caregiver->created = date('Y-m-d H:i:s');

    if ($caregiver->create()) {

        http_response_code(201);

        echo json_encode(array("message" => "Profile was created."));
    } else {

        http_response_code(503);

        echo json_encode(array("message" => "Unable to create profile."));
    }
} else {

    http_response_code(400);

    echo json_encode(array("message" => "Unable to create profile. Data is incomplete."));
}

我非常感谢能帮助我的人。

预检(OPTIONS)请求应该返回HTTP OK(也就是代码200)。

您可以在create.php中测试请求方法,当它是“OPTIONS”时返回200,而不是400(错误请求),因为它现在默认发生在代码的错误分支上。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM