对预检请求的响应未通过访问控制检查:它在 angular 中没有 HTTP ok 状态
Response to preflight request doesn't pass access control check: It does not have HTTP ok status in angular
我正在开发一个网站,使用 angular 和 flask 作为后端,我在后端使用了 flask-cors,并在前端设置了代理 link https://www.positronx.io/handle-cors-in-angular-with-proxy-configuration/#:~:text=Enable%20CORS%20with%20Proxy%20Configuration%20Settings%20in%20Angular.&text=To%20enable%20CORS%20via%20proxy,the%20deliberate%20use%20of%20SSL.
但我总是收到如下错误。请帮我解决这个问题,谢谢
错误:Access to XMLHttpRequest at 'http://127.0.0.1:5000/api/login' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
以下是angular
的程序代码
proxy.conf.json [这是我设置代理的地方]
{
"/api/*": {
"target": "http://127.0.0.1:5000",
"secure": false,
"logLevel": "debug"
}
}
backend-api-service.ts [这是我放置所有 API 服务的地方]
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { catchError, Observable, throwError } from 'rxjs';
import { Login } from '../model/login';
@Injectable({
providedIn: 'root'
})
export class BackendAPIService {
private baseAPI = "http://127.0.0.1:5000/api/"
httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
}
constructor(private httpClient: HttpClient) { }
readCSVForecastFile(): Observable<any> {
return this.httpClient.get(this.baseAPI + 'forecast/4b4315e0-1cb2-4595-9124-99fefa9c63f4/read')
.pipe(catchError(this.errorHandler));
}
login(post: Login): Observable<any>{
return this.httpClient.post(this.baseAPI + 'login', JSON.stringify(post), this.httpOptions)
.pipe(
catchError(this.errorHandler)
)
}
errorHandler(error:any) {
let errorMessage = '';
if(error.error instanceof ErrorEvent) {
errorMessage = error.error.message;
} else {
errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`;
}
return throwError(errorMessage);
}
}
login.ts
export class Login {
email!: string;
password!: string;
}
login.component.ts [这是我的登录组件,当我尝试登录时,总是出现错误]
import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { BackendAPIService } from 'src/app/services/backend-api.service';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
form!: FormGroup ;
logindata = {
email: '',
password: ''
}
private en = {
'lable_emailaddress': 'Email Address',
'leble_enterpassword': 'Enter Password',
'input_email' : 'Email',
'input_password' : 'Password',
'hyperlink_forgotpassword': "Forgot Password?",
'button_login': "Login",
'button_register': 'Register',
'or' : 'Or'
}
private idn = {
'lable_emailaddress': 'Alamat Email',
'leble_enterpassword': 'Ketikkan Kata Sandi',
'input_email' : 'Email',
'input_password' : 'Kata Sandi',
'hyperlink_forgotpassword': "Lupa Kata Sandi?",
'button_login': "Masuk",
'button_register': 'Daftar',
'or' : 'Atau'
}
used_lang = {
'lable_emailaddress': '',
'leble_enterpassword': '',
'input_email' : '',
'input_password' : '',
'hyperlink_forgotpassword': "",
'button_login': "",
'button_register': '',
'or' : ''
}
constructor(private backendAPI: BackendAPIService, private router: Router) {
this.language('idn')
this.form = new FormGroup({
email: new FormControl('', [Validators.required]),
password: new FormControl('', Validators.required)
});
}
title!: "Login";
ngOnInit(): void {
const isLogin = this.isLogin();
window.onload = function(){
if(isLogin == '201'){
document.getElementById('form').style.visibility = 'hidden';
}
}
}
submit(){
console.log(this.form.value);
this.backendAPI.login(this.form.value).subscribe(res => {
console.log('Post created successfully!');
this.router.navigateByUrl('register');
})
}
login(): void{
const data = {
email: this.logindata.email,
password: this.logindata.password
}
}
isLogin(): String{
// contoh aja
return '202'
}
language(lang:string){
if(lang === 'idn'){
this.used_lang = {...this.idn};
} else {
this.used_lang = {...this.en};
}
}
}
login.component.html [这是 html 文件]
<form class="form-body" id="form" [formGroup]="form" (ngSubmit)="submit()">
<div class="row g-3">
<div class="col-12">
<label for="inputEmailAddress" class="form-label">{{used_lang.lable_emailaddress}}</label>
<div class="ms-auto position-relative">
<div class="position-absolute top-50 translate-middle-y search-icon px-3"><i class="bi bi-envelope-fill"></i>
</div>
<input type="email" formControlName="email" class="form-control radius-30 ps-5" id="inputEmailAddress"
placeholder="Email">
</div>
</div>
<div class="col-12">
<label for="inputChoosePassword" class="form-label">{{used_lang.leble_enterpassword}}</label>
<div class="ms-auto position-relative">
<div class="position-absolute top-50 translate-middle-y search-icon px-3"><i class="bi bi-lock-fill"></i></div>
<input type="password" formControlName="password" class="form-control radius-30 ps-5" id="inputChoosePassword"
placeholder="Password">
</div>
</div>
<div class="col-6">
</div>
<div class="col-6 text-end"><a href="authentication-forgot-password.html">{{used_lang.hyperlink_forgotpassword}}</a>
</div>
<div class="col-12">
<div class="d-grid">
<button type="submit" class="btn btn-primary radius-30">{{used_lang.button_login}}</button>
</div>
</div>
<div class="col-12 text-center">
<p class="mb-0">{{used_lang.or}}</p>
</div>
<div class="col-12">
<div class="d-grid">
<a class="btn btn-success radius-30" href="/register">{{used_lang.button_register}}</a>
</div>
</div>
</div>
</form>
以下是Flask的程序代码
app.py [这是我的后端 flask 文件]
from flask import Flask, abort, jsonify, redirect, request, flash, url_for, render_template, make_response
from flask_cors import CORS, cross_origin
from flask_login import login_user, logout_user, login_required,LoginManager,current_user
app = Flask(__name__,template_folder='Templates')
CORS(app, resources={r"/*": {"origins": "*"}})
app.config['CORS_HEADERS'] = 'Content-Type'
@app.route('/login', methods=['POST', 'GET'])
@cross_origin()
def login_post():
if request.method == 'GET':
return render_template('login.html')
if request.method == 'POST':
email = request.form.get('email')
password = request.form.get('password')
user = User.query.filter_by(email=email).first()
if not user and not check_password_hash(user.password, password):
return 'Please check your login details and try again.',400
login_user(user)
return jsonify(current_user.id),200
if __name__ == '__main__':
app.port = 5000
app.run(debug=True)
CORS 应该是 server-side 问题,而不是 Angular。
Anw 仅用于开发目的,您可以使用选项 --disable-web-security 打开 Chrome。您可以在此处查看参考:Disable same origin policy in Chrome
我正在开发一个网站,使用 angular 和 flask 作为后端,我在后端使用了 flask-cors,并在前端设置了代理 link https://www.positronx.io/handle-cors-in-angular-with-proxy-configuration/#:~:text=Enable%20CORS%20with%20Proxy%20Configuration%20Settings%20in%20Angular.&text=To%20enable%20CORS%20via%20proxy,the%20deliberate%20use%20of%20SSL.
但我总是收到如下错误。请帮我解决这个问题,谢谢
错误:Access to XMLHttpRequest at 'http://127.0.0.1:5000/api/login' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
以下是angular
的程序代码proxy.conf.json [这是我设置代理的地方]
{
"/api/*": {
"target": "http://127.0.0.1:5000",
"secure": false,
"logLevel": "debug"
}
}
backend-api-service.ts [这是我放置所有 API 服务的地方]
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { catchError, Observable, throwError } from 'rxjs';
import { Login } from '../model/login';
@Injectable({
providedIn: 'root'
})
export class BackendAPIService {
private baseAPI = "http://127.0.0.1:5000/api/"
httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
}
constructor(private httpClient: HttpClient) { }
readCSVForecastFile(): Observable<any> {
return this.httpClient.get(this.baseAPI + 'forecast/4b4315e0-1cb2-4595-9124-99fefa9c63f4/read')
.pipe(catchError(this.errorHandler));
}
login(post: Login): Observable<any>{
return this.httpClient.post(this.baseAPI + 'login', JSON.stringify(post), this.httpOptions)
.pipe(
catchError(this.errorHandler)
)
}
errorHandler(error:any) {
let errorMessage = '';
if(error.error instanceof ErrorEvent) {
errorMessage = error.error.message;
} else {
errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`;
}
return throwError(errorMessage);
}
}
login.ts
export class Login {
email!: string;
password!: string;
}
login.component.ts [这是我的登录组件,当我尝试登录时,总是出现错误]
import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { BackendAPIService } from 'src/app/services/backend-api.service';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
form!: FormGroup ;
logindata = {
email: '',
password: ''
}
private en = {
'lable_emailaddress': 'Email Address',
'leble_enterpassword': 'Enter Password',
'input_email' : 'Email',
'input_password' : 'Password',
'hyperlink_forgotpassword': "Forgot Password?",
'button_login': "Login",
'button_register': 'Register',
'or' : 'Or'
}
private idn = {
'lable_emailaddress': 'Alamat Email',
'leble_enterpassword': 'Ketikkan Kata Sandi',
'input_email' : 'Email',
'input_password' : 'Kata Sandi',
'hyperlink_forgotpassword': "Lupa Kata Sandi?",
'button_login': "Masuk",
'button_register': 'Daftar',
'or' : 'Atau'
}
used_lang = {
'lable_emailaddress': '',
'leble_enterpassword': '',
'input_email' : '',
'input_password' : '',
'hyperlink_forgotpassword': "",
'button_login': "",
'button_register': '',
'or' : ''
}
constructor(private backendAPI: BackendAPIService, private router: Router) {
this.language('idn')
this.form = new FormGroup({
email: new FormControl('', [Validators.required]),
password: new FormControl('', Validators.required)
});
}
title!: "Login";
ngOnInit(): void {
const isLogin = this.isLogin();
window.onload = function(){
if(isLogin == '201'){
document.getElementById('form').style.visibility = 'hidden';
}
}
}
submit(){
console.log(this.form.value);
this.backendAPI.login(this.form.value).subscribe(res => {
console.log('Post created successfully!');
this.router.navigateByUrl('register');
})
}
login(): void{
const data = {
email: this.logindata.email,
password: this.logindata.password
}
}
isLogin(): String{
// contoh aja
return '202'
}
language(lang:string){
if(lang === 'idn'){
this.used_lang = {...this.idn};
} else {
this.used_lang = {...this.en};
}
}
}
login.component.html [这是 html 文件]
<form class="form-body" id="form" [formGroup]="form" (ngSubmit)="submit()">
<div class="row g-3">
<div class="col-12">
<label for="inputEmailAddress" class="form-label">{{used_lang.lable_emailaddress}}</label>
<div class="ms-auto position-relative">
<div class="position-absolute top-50 translate-middle-y search-icon px-3"><i class="bi bi-envelope-fill"></i>
</div>
<input type="email" formControlName="email" class="form-control radius-30 ps-5" id="inputEmailAddress"
placeholder="Email">
</div>
</div>
<div class="col-12">
<label for="inputChoosePassword" class="form-label">{{used_lang.leble_enterpassword}}</label>
<div class="ms-auto position-relative">
<div class="position-absolute top-50 translate-middle-y search-icon px-3"><i class="bi bi-lock-fill"></i></div>
<input type="password" formControlName="password" class="form-control radius-30 ps-5" id="inputChoosePassword"
placeholder="Password">
</div>
</div>
<div class="col-6">
</div>
<div class="col-6 text-end"><a href="authentication-forgot-password.html">{{used_lang.hyperlink_forgotpassword}}</a>
</div>
<div class="col-12">
<div class="d-grid">
<button type="submit" class="btn btn-primary radius-30">{{used_lang.button_login}}</button>
</div>
</div>
<div class="col-12 text-center">
<p class="mb-0">{{used_lang.or}}</p>
</div>
<div class="col-12">
<div class="d-grid">
<a class="btn btn-success radius-30" href="/register">{{used_lang.button_register}}</a>
</div>
</div>
</div>
</form>
以下是Flask的程序代码
app.py [这是我的后端 flask 文件]
from flask import Flask, abort, jsonify, redirect, request, flash, url_for, render_template, make_response
from flask_cors import CORS, cross_origin
from flask_login import login_user, logout_user, login_required,LoginManager,current_user
app = Flask(__name__,template_folder='Templates')
CORS(app, resources={r"/*": {"origins": "*"}})
app.config['CORS_HEADERS'] = 'Content-Type'
@app.route('/login', methods=['POST', 'GET'])
@cross_origin()
def login_post():
if request.method == 'GET':
return render_template('login.html')
if request.method == 'POST':
email = request.form.get('email')
password = request.form.get('password')
user = User.query.filter_by(email=email).first()
if not user and not check_password_hash(user.password, password):
return 'Please check your login details and try again.',400
login_user(user)
return jsonify(current_user.id),200
if __name__ == '__main__':
app.port = 5000
app.run(debug=True)
CORS 应该是 server-side 问题,而不是 Angular。
Anw 仅用于开发目的,您可以使用选项 --disable-web-security 打开 Chrome。您可以在此处查看参考:Disable same origin policy in Chrome