【发布时间】:2018-07-04 02:03:26
【问题描述】:
我已经使用 spring-boot 和 angular5 构建了一个简单的应用程序,我为没有 spring-security 的 Controller 启用了跨域,该应用程序运行良好,但是当我只是 spring-security 跨域的依赖项时没有不工作,那我该怎么办?
控制器
@RestController
@RequestMapping(ResourceConstants.Product_URL)
@Api(description = "Porduct and Categories resources")
@CrossOrigin
public class ProductResources {
@Autowired
private CategoryRepo cateRepo;
// Categories Resources
@RequestMapping(method = RequestMethod.GET, value = "/AllCategories")
@ApiOperation(value = "Return All Categories")
public List<Category> getAllCategories() {
return cateRepo.findAll();// .stream().
// filter((c)->c.getActive()==1)
// .collect(Collectors.toList());
}}
我的 Angular 5 代码
import { Component, OnInit } from '@angular/core';
import { CategoryService } from '../services/category.service';
import {Http, Response} from "@angular/http";
import { Observable } from 'rxjs/Observable';
import "rxjs/add/operator/map";
import "rxjs/add/operator/catch";
@Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.scss'],
providers: [CategoryService]
})
export class HeaderComponent implements OnInit {
currency = [];
languages = [];
links = [];
constructor(private http: Http) {
this.currency = ['USD', 'Egp'];
this.languages = [
'Arabic',
'English'
];
this.links = ['SignUp', 'Profile', 'Settings', 'SignIn'];
}
ngOnInit() {
console.log("Welcome");
this.getAll()
.subscribe(
data => console.log(data),
err => {
// Log errors if any
console.log(err);
});
}
getAll(): Observable<any> {
//noinspection TypeScriptValidateTypes
return this.http
.get('http://localhost:8080/rest/api/product/AllCategories')
.map(this.mapRoom);
}
mapRoom(response: Response): any[] {
return response.json().content;
}
}
在 google chrome 上运行 angular 5 时出现此错误
GET http://localhost:8080/rest/api/product/AllCategories 401 ()
Failed to load http://localhost:8080/rest/api/product/AllCategories: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 401.
我应该添加什么?
【问题讨论】:
-
您如何为您的 Angular 5 应用程序提供服务?您需要 Angular 5 的 CORS 以允许 localhost:8080
标签: angular spring-boot cors