在将请求从Angular Service发送到Java控制器时,我将面临错误
No 'Access-Control-Allow-Origin'
1.http://localhost:8080/fileValidate 403
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.BELOW是我的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 Controller。
2.真的,我在这个问题上需要帮助,我尝试了我发现的所有可能解决方案
该请求被阻止,因为localhost:8080是一个不同的URL,与localhost:4200。
您必须了解浏览器正在阻止请求,而不是Web服务器。浏览器可能会加载资源,但由于某些Web标准而阻止它。
一个选项是使用相同的端口,以便您获得相同的URL。
另一个选项是允许其他URL/ORIGINS。
因此,您的Web服务器必须使用此标头响应:
Access-Control-Allow-Origin: http://localhost:4200
或允许所有起源:
Access-Control-Allow-Origin: *
编辑:
您现在尝试添加标题,但有错误:
- 请勿将访问控制 - *标头添加到客户端代码中。它们是从服务器发送到客户端的。
在此行中
@crossorigin(origins =" http://localhost:8080/fileValidate"(
您允许错误的起源。起源是http://localhost:4200
如果您仍在获取 no'访问控制 - 允许 - 孔'错误,则可以分析浏览器中的网络流量(Firefox中的F12(。查看标头是否发送以及其值是多少。
也可能有必要设置其他访问控制 - **标题,但是您将收到另一个错误消息。
当您使用弹簧靴时,为什么不添加过滤器。让我给你一个例子。
@Component
public class SimpleCORSFilter implements Filter {
private final Logger log = LoggerFactory.getLogger(SimpleCORSFilter.class);
public SimpleCORSFilter() {
log.info("SimpleCORSFilter init");
}
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With, remember-me");
chain.doFilter(req, res);
}
@Override
public void init(FilterConfig filterConfig) {
}
@Override
public void destroy() {
}
}
我们在这里做什么?我们正在通过特定的HTTP标头启用某些CORS功能,这些HTTP标头告诉浏览器应允许下载网页以向给定/所有域提出Web请求。
您还可以在此上限制http方法(获取/put/post/delete等(。
让我知道您是否需要更多信息。快乐编码
问题是因为您的客户端应用程序和服务器应用程序正在不同域运行。浏览器将在进行实际API调用以检查安全性之前进行options
调用。
即使您在客户端应用程序标头问题中添加Access-Control-Allow origin header
也无法解决。
服务器端解决方案
您已使用任何库中的服务器应用程序启用CORS,或者您已经在后端应用程序中处理options
调用。
处理 options
在有意义的意义上打电话给您解决选项,并用200个响应。
对于每个API,您都可以检查方法以及如果选项方法,则使用200
解决角解决方案
在root目录中创建一个proxy.conf.json
<!-- proxy.conf.json -->
{
"/api/*": {
"target": "http://localhost:8080",
"secure": true,
"logLevel": "debug"
}
}
更改package.json
中的启动脚本<!-- package.json -->
{.
.
.
"scripts": {
"start": "ng serve --proxy-config proxy.conf.json",
.
.
}
将Angular应用程序API调用的基本URL更改为/api/
而不是ng serve
运行npm start
在上述更改时,将没有CORS
问题
注意:您的服务器API终点应该是这样的http:localhost:8000/api/fileValidate
NOTE 在上面的我将/api
添加到API端点,我在proxy.conf.json
希望它能解决您的问题。如果您面临任何困难,请告诉我。