Angular 2 Request头字段在预检响应中,Access-Control-Allow-Headers不允许授权

时间:2017-05-27 05:27:26

标签: codeigniter angular codeigniter-3 codeigniter-restserver

我正在为我的服务器应用程序使用codeigniter REST API。客户端作为Angular2,在我的REST API中,我已经给出了基本的身份验证。我设置了

$config['rest_auth'] = 'basic';

并且

$config['rest_valid_logins'] = ['uname' => 'pwd'];

对于CORS Check我也使用了以下代码,

$config['check_cors'] = TRUE;
$config['allowed_cors_headers'] = [
  'Origin',
  'X-Requested-With',
  'Content-Type',
  'Accept',
  'Access-Control-Request-Method'
];
$config['allowed_cors_methods'] = [
  'GET',
  'POST',
  'OPTIONS',
  'PUT',
  'PATCH',
  'DELETE'
];
$config['allow_any_cors_domain'] = TRUE;

我也试过在我的休息控制器中明确尝试过,

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Content-Range, Content-Disposition, Content-Description');

我在angular中使用了以下代码,

import { Component, OnInit } from '@angular/core';
import { Http, Headers, RequestOptions  } from '@angular/http';
import { FormGroup, AbstractControl, FormBuilder, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { CommonService, BaseAPIURL } from '../common/common.service';
export class Login implements OnInit {
 private headers: Headers;
  constructor(fb: FormBuilder, private router: Router, private http: Http,
    private commonService: CommonService) {
     this.headers = new Headers();
     this.headers.append('Authorization', 'Basic ' + btoa('uname:pwd'));
     this.headers.append('Content-Type', 'application/json');

  }
 ngOnInit() {
  }

  public onSubmit(values: Object): void {
    this.submitted = true;
    if (this.form.valid) {
      let options = new RequestOptions({ headers: this.headers });
      this.http.post(this.getuserLoginURL, JSON.stringify(values),  options ).subscribe(
        response => {
          let result = response.json();
          this.errorMessage = result.message;
        },
        error => {
          this.isDisabled = false;console.log(error);
          if (error.status == 400) {
            this.errorMessage = JSON.parse(error._body).message;
          } else {
            this.errorMessage = 'Internal server error. please contact admin.';
          }
        }, () => {
        });
    }
  }
}

当我与邮递员核实时,它运作良好,没有任何问题。当检查角度误差时,

XMLHttpRequest cannot load http://localhost:97/sencogold/index.php/Adminaccount_api/login_adminuser. Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response.

如果我错误了其余的auth并删除了Authorization标头,那么它运行良好而不检查api用户名和密码

$config['rest_auth'] = FALSE;

并以角度

 this.headers = new Headers();
    //this.headers.append('Authorization', 'Basic ' + btoa('lmxretail:lmx@2017'));
    this.headers.append('Content-Type', 'application/x-www-form-urlencoded');

请帮助任何人为我的api应用身份验证。

3 个答案:

答案 0 :(得分:4)

Authorization添加到CORS检查:

$config['allowed_cors_headers'] = [
  'Authorization',
  'Origin',
  'X-Requested-With',
  'Content-Type',
  'Accept',
  'Access-Control-Request-Method'
];

答案 1 :(得分:1)

为了使您的预检请求成功,服务器控制器必须接受“授权”标头为有效。您可以通过添加“授权”键以及其他允许的标头值来实现:

Access-Control-Allow-Headers: Authorization, Content-Type, Content-Range, Content-Disposition, Content-Description

答案 2 :(得分:0)

在 php codeigniter 后端中,只需将此标头放在 api 控制器的construct() 中即可。 例子:

class ApiController extends CI_Controller {
    function __construct(){
        
            parent::__construct();
            header('Access-Control-Allow-Origin: *');
            header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");            
            header("Access-Control-Allow-Headers: Origin,X-Requested-With,Content-Type,Accept,Access-Control-Request-Method,Authorization,Cache-Control");
            header('Content-Type: application/json'); 
    }
public function index(){
        $MYARRAY = array(1);
        echo json_encode($MYARRAY);
}
}