【发布时间】:2019-08-07 17:15:19
【问题描述】:
当从 Angular 服务发送请求到 java 控制器时,我遇到了错误
No 'Access-Control-Allow-Origin'
1.http://localhost:8080/fileValidate403
2.Access to XMLHttpRequest at 'http://localhost:8080/fileValidate' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
# Angular-Service
1.below is my angular service code.
createFileValidation(filevalidation: Filevalidation): Observable<any> {
var service = "http://localhost:8080/fileValidate";
let body = JSON.stringify(filevalidation);
let headers = this.createHeader();
headers.append('Content-Type', 'application/json');
headers.append('Access-Control-Allow-Origin', '*');
headers.append('Access-Control-Allow-Methods', 'OPTIONS,GET, POST, PUT, PATCH, DELETE');
headers.append('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
headers.append('Access-Control-Allow-Credentials', 'true');
// let options = new RequestOptions({ headers: headers });
return this.http
.post(service, body, { headers: headers })
.map((response: Response) => {
return response.json(); //blob should be use insted of json
//return new Blob([response.blob()], { type: 'text/xml' });
});
}
}
1.下面是我的JAVA控制器代码。
@RestController
@CrossOrigin(origins = "http://localhost:8080/fileValidate")
public class FileValidationController {
@Autowired
private FileValidationService fileService;
String results = "success";
@RequestMapping(value = "/fileValidate", method = RequestMethod.GET, produces = { "application/json" })
@ResponseBody
public ResponseEntity<String> fileService() {
System.out.println("Controller");
HttpHeaders headers = new HttpHeaders();
headers.add("Access-Control-Allow-Origin", "*");
headers.add("Access-Control-Allow-Methods", "OPTIONS,GET, POST, DELETE, PUT");
// .allow("OPTIONS").build();
return new ResponseEntity<String>(fileService.validatefile(),headers, HttpStatus.OK);
}
}
下面的代码是代理设置
{
"/api": {
"target": "http://localhost:8080",
"secure": false
}
}
Angular package.json 这里我已经做了代理设置请看脚本
{
"scripts": {
"ng": "ng",
"start": "ng serve --proxy-config proxy.config.json",
"build": "ng build",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e"
},
- 从 Postman 我可以发送相同的请求,但是当我从浏览器发送相同的请求时,我收到了这个错误,所以我的期望是请求应该到达 JAVA 控制器。
2.在这个问题上我真的需要帮助,我已经尝试了所有可能的解决方案
【问题讨论】:
标签: angular spring-boot