在控制台中运行我的Angular HTTP Get请求时,出现以下错误:
CORS策略已阻止从来源“ http://localhost:4200”访问“ [url]”处的XMLHttpRequest:请求的资源上没有“ Access-Control-Allow-Origin”标头。
我在后端使用了下面的代码,但这不能解决问题。我见过像js语法这样的实现。我需要正确的Java / Angular配置。
app.use(function (req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.setHeader('Access-Control-Allow-Credentials', true);
next();
});
``````````````````````````
private void configureCors(Environment environment) {
final FilterRegistration.Dynamic cors =
environment.servlets().addFilter("CORS", CrossOriginFilter.class);
// Configure CORS parameters
cors.setInitParameter(CrossOriginFilter.ALLOWED_ORIGINS_PARAM, "*");
cors.setInitParameter(CrossOriginFilter.ALLOWED_HEADERS_PARAM, "X-Requested-With,Content-Type,Accept,Origin,Authorization");
cors.setInitParameter(CrossOriginFilter.ALLOWED_METHODS_PARAM, "OPTIONS,GET,PUT,POST,DELETE,HEAD");
cors.setInitParameter(CrossOriginFilter.ALLOW_CREDENTIALS_PARAM, "true");
// Add URL mapping
cors.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*");
}
`````````````````````````````````