No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not allowed access


#1

I am building an app using ionic, Drupal rest api . I get this error on implementing a web service authentification “Failed to load http://localhost/drupal-8.5.3/user/login?_format=json: Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘http://localhost:8100’ is therefore not allowed access.”
I have no idea what should I do to fix this so I hope someone here has an idea what might be causing this.

   public login() {
    let data = JSON.stringify({
        name: this.registerCredentials.name,
        pass: this.registerCredentials.password,
      });
    let apiloginUrl = 'http://localhost/drupal-8.5.3/user/login?_format=json';
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');
   
    this.http.post(apiloginUrl, data, {headers: headers})
        .subscribe(data => {
            localStorage.setItem('loggedinData', data['_body']);
            let apiTokenUrl = 'http://localhost/drupal-8.5.3/oauth/token';
            this.http.get(apiTokenUrl)
                .subscribe(data => {
                    localStorage.setItem('loggedin_token', data['_body']);
                }, error => {
                    console.log(error);// Error getting the data
                });
          this.navCtrl.setRoot(TimelinePage);
        }, error => {
          this.showError("Access Denied");
        });
   }

loginkeyboard() {
    this.keyboard.onKeyboardShow().subscribe(
        data => {
            if(document.getElementById('login')){
                document.getElementById('login').style.height = this.height + 'px';
            }
        }
    );
}

#2

Your API has to return the mentioned header.


#3

how can i resolve the problem ?


#4

Not entirely familiar with Drupal’s API, but I’ve gotten that error before from many other API’s in the past. If Sujan12’s suggestion doesn’t work, it might be because CORS isn’t setup for that particular location/site. I did a quick google to find it there’s a way to set it in Drupal and I found this which might help you resolve the issue.

https://www.drupal.org/node/2715637

Once your localhost app has access to the drupal api you shouldn’t get that error anymore. Hope it helps a little.