由于访问控制检查,XMLHttpRequest无法加载XXXX使用Angular Material MD Stepper时

时间:2022-08-22 10:02:08

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.

我的应用程序在大约一小时前完美运行。现在,我似乎已经陷入困境,想知道为什么特定的https请求不适用于除chrome web之外的所有浏览器。我的第一个假设是CORS。我有原始标题和所有设置,因为我已经有一段时间了。我不知道发生了什么变化。

Here is the error I am getting on Safari

这是我在Safari上遇到的错误

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

由于访问控制检查,XMLHttpRequest无法加载http:// localhost:3000 / auth / server / signup。

Here is my CORS middleware

这是我的CORS中间件

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.

devUrl是一个var作为正确的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.

请求正在为其他http请求工作,它指出我在错误中使用的url是相同/正确的url。我已经被困了一段时间并且认真地需要帮助。我不知道如何调试这个。此外,每次我尝试请求时它都会刷新页面。我不知道该怎么做。


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

这是我发送http请求的客户端代码

@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.

***更新我将登录按钮从角度材料md-step元素内部移动到它之外,它工作正常。不知道这里发生了什么,但这似乎是个问题。

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

以下是上面的代码,导致非Chrome Web浏览器出现CORS问题

<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>

2 个解决方案

#1


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...

乔纳森的回答似乎是正确的。显然Apple决定html按钮只是一个按钮,如果它有type =“button”,即使type = submit也会抛出同样的错误......

#2


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.

任何人在谷歌资料中遇到md-step或Stepper的问题。尝试在每个步骤中添加type =“button”。我觉得很奇怪我收到了一个CORS错误,但它确实有效。

#1


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...

乔纳森的回答似乎是正确的。显然Apple决定html按钮只是一个按钮,如果它有type =“button”,即使type = submit也会抛出同样的错误......

#2


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.

任何人在谷歌资料中遇到md-step或Stepper的问题。尝试在每个步骤中添加type =“button”。我觉得很奇怪我收到了一个CORS错误,但它确实有效。