Java 没有';访问控制允许原点';请求的资源上存在标头。错误
我在前端使用Angular,在后端使用Java Spring,但我得到了一个错误:Java 没有';访问控制允许原点';请求的资源上存在标头。错误,java,spring,angular,Java,Spring,Angular,我在前端使用Angular,在后端使用Java Spring,但我得到了一个错误:请求的资源上没有“Access Control Allow Origin”头。,而我确信CORS已启用。这是我的配置文件: package com.aon04.backend.configuration; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.confi
请求的资源上没有“Access Control Allow Origin”头。
,而我确信CORS已启用。这是我的配置文件:
package com.aon04.backend.configuration;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
@EnableWebMvc
public class CorsConfiguration implements WebMvcConfigurer
{
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**");
}
}
它工作正常,我可以毫无问题地执行其他每个请求,但我服务中的这个PUT请求给了我一个错误:
updateExamById(id, exam: Examen): Observable<Examen> {
return this.http.put<Examen>(APIURL + '/update/' + id, {file: exam.file, name: exam.naam});
}
无需添加此配置
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**");
}
只需在类级或方法级的控制器类中添加您想要的
@CrossOrigin(origins = "http://localhost:4200")
你还有其他的工作PUT请求吗?没有,只有GET请求。这可能是有角度的。您可能需要一个过滤器或其他东西来返回CORS头以响应选项请求。尝试我尝试了WebSecurityConfigureAdapter答案,但它不起作用,仍然是同一个错误。问题是我没有返回响应标题,而是返回了一个测试。您的服务中也可能存在标题问题,因此如果跨源不起作用,请在您的服务中使用“const headers1=new HttpHeaders”添加标题({'Content-Type':'application/json;charset=utf-8'});“在我的例子中,当从angular的末尾为post请求调用rest api时,您可以将其作为第三个参数添加到put请求中,而无需在post请求中添加标题。我只是在我的控制器类中添加了@annotation。如果您想做更多的CORS过滤,那么您还可以添加CORSfilter.java(在google上搜索)这会过滤请求。
@CrossOrigin(origins = "http://localhost:4200")