Angular项目跳转id undefined及CORS缺少Access-Control-Allow-Origin头报错
问题1:CORS header 'Access-Control-Allow-Origin' missing 报错解决
- 报错原因:浏览器同源策略限制,本地开发环境域名(http://localhost:4200)和接口域名(https://fireman-7cc06-default-rtdb.firebaseio.com/)不同源,且服务端未配置跨域许可头。
- 开发阶段临时解决:使用Angular内置代理转发请求
- 在项目根目录新建
proxy.conf.json文件,内容如下:
- 在项目根目录新建
{ "/api": { "target": "https://fireman-7cc06-default-rtdb.firebaseio.com/", "secure": true, "changeOrigin": true, "pathRewrite": { "^/api": "" } } }
- 修改
angular.json文件中projects -> 你的项目名 -> architect -> serve -> options配置,新增字段:
"proxyConfig": "proxy.conf.json"
- 修改service中的baseurl为
/api,重启开发服务即可生效
- 生产环境解决:在Firebase Realtime Database的规则配置中添加跨域许可,或通过自有后端服务转发接口请求。
问题2:路由跳转id为undefined解决
该问题存在两处代码错误,分别修复即可:
错误1:列表页路由绑定取值错误
从列表页字段取值逻辑info[1]?.Item_name可判断,遍历对象info是Firebase返回数据转数组后的[数据id, 数据内容]结构,不存在info.id属性,需要改为取数组第一位的id值。
修改list-item组件html中的跳转代码:
<!-- 原错误代码 --> <i [routerLink]="['/view/',info.id]" class="fa fa-eye" aria-hidden="true"></i> <!-- 修改后代码 --> <i [routerLink]="['/view/',info[0]]" class="fa fa-eye" aria-hidden="true"></i>
错误2:详情页参数获取逻辑时序错误
ActivatedRoute.params的订阅是异步操作,原代码中接口请求逻辑写在订阅外部,会导致还未拿到id就已经执行了请求逻辑。修改view-component.ts的ngOnInit代码:
ngOnInit(): void { this.activateroute.params.subscribe(data => { this.viewId = data.id; // 拿到id后再执行接口请求 if (this.viewId) { console.log(this.viewId) this.itemservices.viewFunction(this.viewId).subscribe(data => { this.viewItems = data }, err => { console.log('data not get' + err) }) } }, err => { console.log('id not get' + err) }) }
内容的提问来源于stack exchange,提问作者Manu Sunny
相关产品推荐
相关产品推荐

