没有带有弹簧后端、角度应用程序和 nginx 的“Access-Control-Allow-Origin”标头
Posted
技术标签:
【中文标题】没有带有弹簧后端、角度应用程序和 nginx 的“Access-Control-Allow-Origin”标头【英文标题】:No 'Access-Control-Allow-Origin' header with spring backend, angular app and nginx 【发布时间】:2021-08-30 18:39:41 【问题描述】:我正在努力处理 CORS 标头。 我有 2 个带有 nginx 的 EC2 实例,一个用于 angular 的前端,一个用于带有 spring 的后端
当前端调用这个资源时:
Request URL: https://backend.myhost.com/v1/assignments
Access-Control-Request-Origin: https://myhost.com/
Authorization: Basic somebasicauth
Content-Type: application/json
我有:
Access to XMLHttpRequest at 'https://backend.myhost.com/v1/assignments' from origin
'https://myhost.com' 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.
我认为我的 spring 配置应该没问题。我不确定错误在哪里。
这是我的 Spring 配置:
@Override
public void addCorsMappings(CorsRegistry registry)
registry.addMapping("/**")
.allowedMethods("POST", "GET", "PUT", "HEAD", "DELETE")
.allowedOrigins("https://myhost.com", "http://backend.myhost.com")
.allowedHeaders("Content-Type", "X-Requested-With", "accept", "Origin", "Access-
Control-Request-Method",
"Access-Control-Request-Headers")
.exposedHeaders("Access-Control-Allow-Origin", "Access-Control-Allow-
Credentials").allowCredentials(true).maxAge(3600);
@Override
protected void configure(HttpSecurity http) throws Exception
http.csrf().disable()
.authorizeRequests().anyRequest().authenticated()
.and()
.cors().and()
.httpBasic().authenticationEntryPoint(authenticationEntryPoint());
控制器:
@ResponseStatus(HttpStatus.CREATED)
@ApiResponses(value =
@ApiResponse(code = 201, message = "Messages successfully sent"),
@ApiResponse(code = 400, message = "Sanitization error, malicious input", response =
ErrorDetailsDto.class)
)
@ApiOperation(value = "Send assingments",
notes = "This method creates assignment")
@PostMapping(produces = MediaType.APPLICATION_JSON_VALUE, consumes =
MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Object> create(@RequestBody() @Validated final
AssignmentDto dto)
some code
角度拦截器:
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>>
this.spinnerService.requestStarted();
request = request.clone(
setHeaders:
Authorization: 'Basic ' + btoa('user:pw'),
Accept: 'application/json',
'Content-Type': 'application/json',
'Access-Control-Request-Origin': 'https://myhost.com/'
);
return this.handler(next, request);
请求:
public postAssignments(): Observable<any>
this.requestBody = this.wichtelDataHandler.getDto();
return this.http.post<any>('https://backend.myhost.com/v1/assignments',
this.requestBody, observe: 'response');
在 nginx 配置文件中没有针对 cors 的特殊设置。
我需要更改什么,该请求未被拒绝?
【问题讨论】:
我希望得到关于否决票的反馈,以改进进一步的问题。我能做些什么更好?我认为问题陈述很清楚。只有需要理解的代码才提供最低需求信息。我还能做得更好吗? 【参考方案1】:只需将 Spring Config 更改为
.allowedOrigins("*")
【讨论】:
我知道我可以做到这一点,但我的目标只是允许我的已知来源以上是关于没有带有弹簧后端、角度应用程序和 nginx 的“Access-Control-Allow-Origin”标头的主要内容,如果未能解决你的问题,请参考以下文章