简体   繁体   中英

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

I'm trying to set up an angular app with a simple CRUD API in the backend. I have some problems with the CORS policy and I haven't found the right solution to solve my error. I'm trying to create a user (caregiver) through an angular form.

I think I have more than the necessary headers in my php api. I've put them in an .htaccess file:

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"

And I can also see them in my Chrome console when I try the request:

请求

As you can see I get the status code 400: bad request, but it's on my OPTIONS request, so before I can even POST my form data.

Then this is the error I'm getting in my chrome console: 安慰 So I assume this is the problem:

Access to XMLHttpRequest at ' http://localhost/api_pillassist/caregiver/create.php ' from origin >' http://localhost:8000 ' has been blocked by CORS policy: Response to >preflight request doesn't pass access control check: It does not have HTTP ok >status.

I've also already downloaded the chrome extension that enables 'Allow control allow origin: *', but even that doesn't work.

I'll provide some of my code below, although I'm not sure the problem lies there. I've also tried to send my POST request with form data in Postman and this works, so I don't know if this is any useful, but I'll include it anyway:

Here's the component-template I use in my angular app:

<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>

This is the 'createCaregiver()' function it links to:

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))
    );
  }
}

This is the caregiverService file:

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)
      );
  }

And this is in my api what I have in the create.php file:

<?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."));
}

I would be very grateful to anyone who can help me.

The preflight (OPTIONS) request should return HTTP OK (aka code 200).

You can test the request method in your create.php and return 200 when it is "OPTIONS", not 400 (bad request) as it happens now by default on the error branch of your code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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