Javascript 使用 Angular Material MD Stepper 时,由于访问控制检查,XMLHttpRequest 无法加载 XXXX
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46417288/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
XMLHttpRequest cannot load XXXX due to access control checks When using Angular Material MD Stepper
提问by Jonathan Corrin
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/signupdue 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();
});
devUrlis 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 网络浏览器上的 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>
采纳答案by Jonathan Corrin
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 错误,但它有效。
回答by David Cardoso
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 也会抛出同样的错误......

