Search code examples
codeigniterangular2-servicesangular2-directives

Angular 2 with codeigniter api Does Not Working


I have used angular 2 front end i send my api request into the codeigniter i have get below error in console

Failed to load http://localhost/cli-scr1/api/login: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.

This is my api call function,

  islogin(info){
      console.log(info);
      return this.http.post("http://localhost/cli-scr1/api/login",info)
      .map(res => {
          if(res.json()){
                var arr = Object.values(res.json()[0]);
                console.log(arr[0]['name']);
                localStorage.setItem("userName",arr[0]['name']);
                this.router.navigate(['/home']);
          }else{
              this.router.navigate(['/login']);
          }

      }
     );  
  }

And this is my codeigniter Function,

public function index()
    {

        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Headers: X-Requested-With');
        header('Access-Control-Allow-Methods: POST,GET,OPTIONS');

        print_r($this->input->post());

    } 

Solution

  • Maybe this occurs because the default content type of angular is application/json which will trigger the preflighted request.

    Try to append Content-Type header in the back end :

    header('Access-Control-Allow-Headers: X-Requested-With,Content-Type');