Angular前端请求Flask后端接口失败,寻求解决方案
解决方案
1. 解决跨域(CORS)问题
Angular运行在localhost:4200,Flask运行在localhost:5000,属于不同端口,浏览器会拦截跨域请求,必须在Flask中配置CORS:
- 安装依赖:
pip install flask-cors - 修改Flask的
app.py,添加CORS配置:from flask import Flask, jsonify from flask_cors import CORS app = Flask(__name__) # 开发环境允许4200端口跨域,生产环境可指定具体域名 CORS(app, origins="http://localhost:4200") @app.route('/getconcepts', methods=['GET']) def get_concepts(): # 替换为你的业务逻辑,这里用示例数据 concepts = ["概念1", "概念2", "概念3"] return jsonify(concepts) if __name__ == '__main__': app.run(port=5000, debug=True)
2. 修正Angular代码中的拼写错误
客户端代码存在两处变量拼写错误,会导致数据处理失败:
export class LeftNavigationComponent implements OnInit { archiveLinkList: Archivelink[] = []; constructor(private http: HttpClient) {} ngOnInit(): void { this.http.get<string[]>('http://localhost:5000/getconcepts').subscribe( (concepts: string[]) => { // 修正:conceptos → concepts this.archiveLinkList = concepts.map((concept, index) => ({ id: index, concept: encodeURIComponent(concept), // 修正:concepto → concept url: `/display?concept=${encodeURIComponent(concept)}` })); }, error => { console.error('Error fetching concepts:', error); } ); } }
3. 确保Angular导入HttpClientModule
检查根模块(如AppModule)是否导入HttpClientModule,否则HttpClient无法正常工作:
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { HttpClientModule } from '@angular/common/http'; import { LeftNavigationComponent } from './left-navigation/left-navigation.component'; @NgModule({ declarations: [LeftNavigationComponent], imports: [BrowserModule, HttpClientModule], bootstrap: [LeftNavigationComponent] }) export class AppModule { }
4. 验证Flask路由的正确性
确保Flask路由函数缩进正确(你提供的代码中def get_concepts():有多余缩进,会导致语法错误),启动Flask后直接访问http://localhost:5000/getconcepts,确认能返回正确的JSON数据。
内容的提问来源于stack exchange,提问作者Seyarei
相关产品推荐
相关产品推荐

