通过角度6访问rest-api时出现CORS错误
Posted
技术标签:
【中文标题】通过角度6访问rest-api时出现CORS错误【英文标题】:Getting CORS error while accessing rest-api through angular 6 【发布时间】:2019-12-25 16:57:17 【问题描述】:通过angular6访问rest-api时出现CORS错误
import Component, OnInit from '@angular/core';
import TestService from '../../test.service';
import HttpClient from '@angular/common/http';
@Component(
selector: 'app-view-component',
templateUrl: './view-component.component.html',
styleUrls: ['./view-component.component.css']
)
export class ViewComponentComponent implements OnInit
username:string="";
response:any;
public httpOptions : any;
constructor(private http: HttpClient)
ngOnInit()
search()
this.http.get('http://localhost:8080/restapiapp/webapi/profiles')
.subscribe((response)=>
this.response=response;
console.log("Got the response");
console.log(this.response);
)
在我的控制台上出现错误
SEC7120:[CORS] 源“http://localhost:4200”在“http://localhost:8080/restapiapp/webapi/profiles”的跨源资源的 Access-Control-Allow-Origin 响应标头中找不到“http://localhost:4200”。
错误:进度事件
标题:对象 消息:“http://localhost:8080/restapiapp/webapi/profiles 的 Http 失败响应:0 未知错误” 名称:“HttpErrorResponse” 好的:假的 状态:0 statusText:“未知错误” 网址:“http://localhost:8080/restapiapp/webapi/profiles”
原型:对象
【问题讨论】:
您的 API 是否支持 CORS?这可能不是angular HttpClient
问题
如何将 CORS 添加到我的 api 中??
你的 API 是用 NodeJs、.Net、Spring 构建的吗? ...?那应该是另一个问题?
它在 spring-boot 上
查看这个帖子***.com/questions/51720552/…
【参考方案1】:
只需添加 CrossOrigin 注释即可工作
【讨论】:
以上是关于通过角度6访问rest-api时出现CORS错误的主要内容,如果未能解决你的问题,请参考以下文章
尝试将数据从角度项目发布到 Spring Web 服务项目时出现 CORS 错误
尝试访问本地 json 文件时出现 CORS 错误 [重复]