XMLHttpRequest cannot load XXXX due to access control checks When using Angular Material MD Stepper

35,218

Solution 1

Anyone having this issue with md-step or Stepper in google material. Try adding type="button" to each step. I find it odd I was receiving a CORS error but it worked.

Solution 2

Jonathan answer seems correct. Apparently Apple decided that a html button is only a button if it has type="button" even the type=submit will throw the same error...

Share:
35,218
Jonathan Corrin
Author by

Jonathan Corrin

Updated on December 05, 2020

Comments

  • Jonathan Corrin
    Jonathan Corrin over 3 years

    My application worked perfectly until about an hour ago. Now I seem to be in limbo about figuring out why specific https requests are not working all browsers aside from chrome web. My first assumption is CORS. I have origin headers and everything set up as I have had for some time. Im not sure what changed.

    Here is the error I am getting on Safari

    XMLHttpRequest cannot load http://localhost:3000/auth/server/signup due to access control checks.

    Here is my CORS middleware

    app.use(function (req,res,next) {
        res.header("Access-Control-Allow-Origin", devUrl);
        res.header('Access-Control-Allow-Methods', 'PUT, PATCH, GET, POST, DELETE, OPTIONS');
        res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        res.setHeader('Access-Control-Allow-Credentials', true);
      next();
    });
    

    devUrl is a var as the correct URL.

    Here are the calls in node that are not working

    var express = require('express');
    var router = express.Router();
    var authController = require('../controllers').auth;
    var jwt = require('jsonwebtoken');
    
    
    router.post('/server/signup', function(req,res,next) {
      return authController.signup(req,res);
    });
    
    router.post('/server/signin', function(req,res,next) {
      return authController.signin(req,res);
    });
    
    router.post('/server/social-signin', function(req,res,next) {
      return authController.authSignin(req,res);
    });
    
    
    module.exports = router;
    

    Requests are working for other http requests and the url that it states I used in the error is the same/correct url. Ive been stuck for a while now and seriously need help. I have no idea how to debug this. Also, it refreshes the page every time I attempt the request as well. Im not sure what to do.


    The last route for social login is working?? Its only sign in and sign up that are affected

    Here is my client-side code where the http requests are sent

    @Component({
      selector: 'app-signin',
      template: `    
        <!-- Main container -->
        <md-toolbar>
          <h5 style="margin: 0 auto;font-family: 'Ubuntu', sans-serif;">Signin</h5>
        </md-toolbar>
        <section class="section">
          <md-horizontal-stepper [linear]="isLinear" *ngIf="!loggingin" style="text-align: center; max-width: 500px; margin: 0 auto">
            <md-step [stepControl]="firstFormGroup">
              <form [formGroup]="firstFormGroup">
                <ng-template mdStepLabel>Email</ng-template>
                <md-form-field>
                  <input mdInput placeholder="Enter Email" formControlName="firstCtrl" [(ngModel)]="user.email" required>
                </md-form-field>
                <div>
                  <button md-button mdStepperNext><p class="p2">NEXT</p></button>
                </div>
              </form>
            </md-step>
            <md-step [stepControl]="secondFormGroup">
              <form [formGroup]="secondFormGroup">
                <ng-template mdStepLabel>Password</ng-template>
                <md-form-field>
                  <input type="password" mdInput placeholder="Enter Password" formControlName="secondCtrl" [(ngModel)]="user.password" required>
                </md-form-field>
                <div>
                  <button md-button mdStepperPrevious><p class="p2">BACK</p></button>
                  <button md-button (click)="onSignin('rent')"><p class="p2">SIGNIN</p></button>
                </div>
              </form>
            </md-step>
          </md-horizontal-stepper>
    
          <p style="text-align: center; font-size: x-large" *ngIf="!loggingin">signin with social</p>
    
          <div style="margin: 30px auto; text-align: center" *ngIf="!loggingin">
            <button md-mini-fab
                    (click)="onSignin('facebook')" style="background-color: #3b5998!important;">
              <span class="fa fa-facebook" style="font-size: x-large; color: white;"></span>
            </button>
            <button md-mini-fab
                    (click)="onSignin('google')" style="background-color: #D84B37!important;">
              <span class="fa fa-google" style="font-size: x-large; color: white;"></span>
            </button>
          </div>
        </section>
        <button md-raised-button (click)="test()">TEST</button>
        <md-spinner *ngIf="loggingin" style="margin: 30px auto"></md-spinner>
      `,
      styleUrls: ['./user.component.css']
    })
    export class SigninComponent implements OnInit {
      loggingin = false;
      user: User = {
        email: '',
        password: '',
        image: '',
        name: '',
        provider: '',
        uid: ''
      };
      signin = false;
      contact = false;
      isLinear = true;
      firstFormGroup: FormGroup;
      secondFormGroup: FormGroup;
    
    
    
      constructor(
        private _formBuilder: FormBuilder,
        private userS: UserService,
        private uis: UiService,
        private authS: MyAuthService,
        private router: Router) { }
    
      ngOnInit() {
        this.firstFormGroup = this._formBuilder.group({
          firstCtrl: ['', Validators.required]
        });
        this.secondFormGroup = this._formBuilder.group({
          secondCtrl: ['', Validators.required]
        });
      }
    
    
      test() {
        let newUser = new User (
          null,
          'XXXX',
          'XXXX'
        );
        console.log(newUser);
        this.authS.onSignin(newUser)
          .subscribe(data => {
            console.log(data);
            localStorage.setItem('token', data['token']);
            localStorage.setItem('userId', data['userId']);
          })
      }
    
    
      onSignin(s: string) {
        this.loggingin = true;
        if (s === 'rent') {
          this.authS.onSignin(this.user)
            .subscribe(user => {
              localStorage.setItem('token', user['token']);
              localStorage.setItem('userId', user['userId']);
              this.userS.getUser()
                .subscribe(user => {
                  if (user.needsToRate !== 0) {
                    this.router.navigate(['/review']);
                    this.uis.onFlash('Signed In Successfully', 'success');
                    this.loggingin = false;
                  } else if (!user.finishedTutorial) {
                    this.router.navigate(['/tutorial']);
                    this.uis.onFlash('Signed In Successfully', 'success');
                    this.loggingin = false;
                  } else {
                    this.router.navigate(['/']);
                    this.uis.onFlash('Signed In Successfully', 'success');
                    this.loggingin = false;
                  }
                }, resp => {
                  console.log(resp);
                });
            }, err => {
              console.log(err);
              if (err.status === 404) {
                this.loggingin = false;
                this.uis.onFlash('Email Not Found', 'error');
              } else if (err.status === 401) {
                this.loggingin = false;
                this.uis.onFlash('Incorrect Username or Password', 'error');
              } else {
                this.loggingin = false;
                this.uis.onFlash('Error Signing In', 'error');
              }
            });
        } else {
          this.authS.authSignin(s)
            .subscribe( authUser => {
              this.authS.onAuthToken(authUser)
                .subscribe(token => {
                  localStorage.setItem('token', token['token']);
                  localStorage.setItem('userId', token['userId']);
                  this.userS.getUser()
                    .subscribe(user => {
                      if (user.needsToRate !== 0) {
                        this.router.navigate(['/review']);
                        this.uis.onFlash('Signed In Successfully', 'success');
                        this.loggingin = false;
                      } else if (!user.finishedTutorial) {
                        this.router.navigate(['/tutorial']);
                        this.uis.onFlash('Signed In Successfully', 'success');
                        this.loggingin = false;
                      } else {
                        this.loggingin = false;
                        this.router.navigate(['/']);
                        setTimeout(() => {
                          location.reload();
                        },500);
                        this.uis.onFlash('Signed In Successfully', 'success');
                      }
                    }, resp => {
                      console.log(resp);
                    });
                }, error => {
                  console.log(error);
                  this.loggingin = false;
                  this.uis.onFlash('Error Signing In', 'error');
                });
          })
        }
      }
    
    }
    

    *** UPDATE I moved the signin button from inside the angular material md-step element to outside it and it worked fine. Not sure whats going on here but this seems to be the issue.

    Here is the code from above causing the CORS problem on non chrome web browsers

    <md-horizontal-stepper [linear]="isLinear" *ngIf="!loggingin" style="text-align: center; max-width: 500px; margin: 0 auto">
                <md-step [stepControl]="firstFormGroup">
                  <form [formGroup]="firstFormGroup">
                    <ng-template mdStepLabel>Email</ng-template>
                    <md-form-field>
                      <input mdInput placeholder="Enter Email" formControlName="firstCtrl" [(ngModel)]="user.email" required>
                    </md-form-field>
                    <div>
                      <button md-button mdStepperNext><p class="p2">NEXT</p></button>
                    </div>
                  </form>
                </md-step>
                <md-step [stepControl]="secondFormGroup">
                  <form [formGroup]="secondFormGroup">
                    <ng-template mdStepLabel>Password</ng-template>
                    <md-form-field>
                      <input type="password" mdInput placeholder="Enter Password" formControlName="secondCtrl" [(ngModel)]="user.password" required>
                    </md-form-field>
                    <div>
                      <button md-button mdStepperPrevious><p class="p2">BACK</p></button>
                      <button md-button (click)="onSignin('rent')"><p class="p2">SIGNIN</p></button>
                    </div>
                  </form>
                </md-step>
              </md-horizontal-stepper>
    
  • Wedge Martin
    Wedge Martin over 6 years
    Yep. Super lame.