简体   繁体   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

I'm trying to set up an angular app with a simple CRUD API in the backend. 我正在尝试在后端设置一个带有简单CRUD API的角度应用程序。 I have some problems with the CORS policy and I haven't found the right solution to solve my error. 我在CORS策略方面遇到了一些问题,但我找不到正确的解决方案来解决我的错误。 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. 我想我的php api中有超过必要的标题。 I've put them in an .htaccess file: 我把它们放在.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"

And I can also see them in my Chrome console when I try the request: 我在尝试请求时也可以在Chrome控制台中看到它们:

请求

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

Then this is the error I'm getting in my chrome console: 那么这就是我在chrome控制台中遇到的错误: 安慰 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. 来自origin>' http:// localhost:8000 '的' http://localhost/api_pillassist/caregiver/create.php '访问XMLHttpRequest已被CORS策略阻止:响应>预检请求未通过访问控制检查:它没有HTTP ok> status。

I've also already downloaded the chrome extension that enables 'Allow control allow origin: *', but even that doesn't work. 我还已经下载了chrome扩展,它允许'允许控制允许来源:*',但即使这样也行不通。

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: 我也尝试在Postman中发送带有表单数据的POST请求,这样可行,所以我不知道这是否有用,但无论如何我都会包含它:

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: 这是它链接到的'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))
    );
  }
}

This is the caregiverService file: 这是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)
      );
  }

And this is in my api what I have in the create.php file: 这是在我的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."));
}

I would be very grateful to anyone who can help me. 我非常感谢能帮助我的人。

The preflight (OPTIONS) request should return HTTP OK (aka code 200). 预检(OPTIONS)请求应该返回HTTP OK(也就是代码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. 您可以在create.php中测试请求方法,当它是“OPTIONS”时返回200,而不是400(错误请求),因为它现在默认发生在代码的错误分支上。

暂无
暂无

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

相关问题 Laravel 从源访问 XMLHttpRequest 已被 CORS 策略阻止 - Laravel Access to XMLHttpRequest at from origin has been blocked by CORS policy 如何解决这个&#39;http://localhost:8080&#39;已被CORS策略阻止:响应预检请求没有通过vueJS中的访问控制? - How to solve this 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control in vueJS? 已被 CORS 政策阻止:无“访问控制允许来源” - has been blocked by CORS policy: No 'Access-Control-Allow-Origin' 访问 abcd.com 上的字体已被 CORS 政策阻止:没有“访问控制允许来源” - Access to Font at abcd.com has been blocked by CORS policy: No 'Access-Control-Allow-Origin' PHP-CORS策略已阻止对字体的访问:没有“ Access-Control-Allow-Origin”标头 - PHP - Access to Font has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header XMLHttpRequest 无法加载。 Access-Control-Allow-Origin 不允许 Origin http://localhost:63342 - XMLHttpRequest cannot load . Origin http://localhost:63342 is not allowed by Access-Control-Allow-Origin 无法在React中使用GraphQL查询-已被CORS策略阻止:所请求的资源上不存在“ Access-Control-Allow-Origin”标头 - Cannot use GraphQL queries in React - has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource Laravel 在“localhost:http://127.0.0.1:8000/”中显示错误 - Laravel shows error in “localhost:http://127.0.0.1:8000/” Flutter - XMLHttpRequest 已被 CORS 政策阻止 - Flutter - XMLHttpRequest has been bloked by CORS policy XAMPP 服务器已被 CORS 策略阻止: - XAMPP Server has been blocked by CORS policy:
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM