API调用后端PHP中的角交叉起源问题?

时间:2019-02-11 09:39:00

标签: php angular codeigniter

当我尝试在本地主机与另一个域之间进行API调用时,遇到了CORS问题,我遇到了404问题。

1。前端:Angualr 7

前端请求部分:

const httpOptions = {
    headers: new HttpHeaders({
      'Content-Type':  'application/json',
      'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Credentials': 'true',
        'Access-Control-Allow-Methods':'POST',
        'Access-Control-Allow-Headers': 'Content-Type'
    })
  }
login(username: string, password: string) {
        return this.http.post<any>('http://remote/djaxtesting/enter_uiupgrade/index.php/api/v1/user/validate',
        {acc_type: "ADMIN", uemail: "djax_admin@dreamajax.com", upw: "123456"},httpOptions)
            .pipe(map(user => {}))


    }

后端编码:

<?php defined('BASEPATH') OR exit('No direct script access allowed');
header ("Access-Control-Allow-Origin: *");
header ("Access-Control-Allow-Credentials: true");
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type');
header('Content-Type: application/json');

    public function validate_post()
    {

        $role = array('ADVERTISER','TRAFFICKER','ADMIN','MANAGER');

        if($this->post('acc_type') !='' and in_array($this->post('acc_type'),$role))
        {

            switch(strtoupper($this->post('acc_type')))
            {
                case "ADMIN":

                    $adminObj   =   $this->do_networks->validate_user($this->post('uemail'),$this->post('upw'),$this->post('acc_type'));
                    //$this->response($adminObj, 200);
    }
    }
    }

enter image description here

我们将php用于api。帮助搬运需要解决此问题?

1 个答案:

答案 0 :(得分:0)

选项方法的问题。选项请求应为200,返回空响应。然后浏览器将发送真实的POST请求。

,用构造函数中PHP文件中的标头替换。它将起作用。

header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method, Authorization");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
   $method = $_SERVER['REQUEST_METHOD'];
   if ($method == "OPTIONS") {
       die();
   }