我很难在Java应用程序中发布数据,因为我的Angular发送了一个http方法Option。
纠正的错误是:
对预检请求的响应未通过访问控制检查:否 请求中存在“ Access-Control-Allow-Origin”标头 资源。因此,不允许原点“ http://localhost:4200” 访问。
我的API安全配置:
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity
.csrf().disable()
.exceptionHandling()
.authenticationEntryPoint(unauthorizedHandler)
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
.antMatchers("/api/instituicao/BuscarTodos", "/auth/**",
"/api/curso/BuscarEquipePorIdInstituicao/**",
"/api/turma/BuscarPorCursoId/**", "/api/cargo/BuscarPorInstituicaoId/**",
"/api/aluno/cadastrar/**", "/api/aluno/BuscarPorMatricula/**",
"/api/servidor/cadastrar/**", "/api/servidor/BuscarPorMatricula/**", "/api/estado/BuscarTodos/**",
"/api/municipio/BuscarPorIdEstado/**", "/v2/api-docs",
"/swagger-resources/**", "/configuration/security", "/swagger-ui.html", "/webjars/**")
.permitAll().anyRequest().authenticated();
httpSecurity.addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class);
httpSecurity.headers().cacheControl();
我的Angular应用程序服务设置标题:
let httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Credentials': 'true',
'Access-Control-Allow-Methods': 'GET,PUT,POST,DELETE,OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type'
})
};
/**
* Retorna o header a ser usado na requisição e caso o usuário possua token ele é adicionado na requisição.
* @param filter parametro a ser adicionado no cabecalho
*/
export function getHeader(filter: any = null) {
let params: HttpParams = new HttpParams();
if (filter != null)
Object.keys(filter).map(k => params = params.set(k, filter[k]));
Object.assign(httpOptions, httpOptions, { params: params });
if (localStorage.getItem('token') != null)
httpOptions.headers = httpOptions.headers.set('Authorization', `Bearer ${localStorage.getItem('token')}`);
return httpOptions;
我发布实体的服务:
Post<T>(route: string, obj: any) {
return this.http.post<T>(`${environment.apiEndPoint}${route}/cadastrar`, obj, getHeader())
.pipe(catchError(this.handleError));
}
我的控制器:
@RestController
@CrossOrigin(origins = "*", allowedHeaders = "*")
@RequestMapping("api/instituicao")
public class InstitutoController extends baseController<InstituicaoDTO, Instituicao, InstituicaoService> {
{
mappingDTOToEntity = new Extension<>(InstituicaoDTO.class, Instituicao.class);
mappingEntityToDTO = new Extension<>(Instituicao.class, InstituicaoDTO.class);
}
protected Extension<EnderecoDTO, Endereco> mappingEntityChild = new Extension<>(EnderecoDTO.class, Endereco.class);
...... @PostMapping
public ResponseEntity<Response<InstituicaoDTO>> cadastrarInstituicao(
@Valid @RequestBody InstituicaoDTO instituicaoDTO, BindingResult result) throws NoSuchAlgorithmException {
log.info("Cadastrando a instituicao: {}", instituicaoDTO.toString());
this.entityService.BuscarPorNomeInstituicao(instituicaoDTO.getNome())
.ifPresent(inst -> result.addError(new ObjectError("instituicao", "Nome já cadastrado.")));
if (result.hasErrors()) {
log.error("Erro ao validar dados da nova instituicao: {}", result.getAllErrors());
result.getAllErrors().forEach(error -> response.getErrors().add(error.getDefaultMessage()));
return ResponseEntity.badRequest().body(response);
}
entity = mappingDTOToEntity.AsGenericMapping(instituicaoDTO);
List<Endereco> listaEnderecos = entity.getEndereco();
entity.setEndereco(new ArrayList<Endereco>());
if (!listaEnderecos.isEmpty())
listaEnderecos.forEach(endereco -> entity.AdicionarEndereco(endereco));
entity = this.entityService.Salvar(entity);
response.setData(mappingEntityToDTO.AsGenericMapping(entity));
return ResponseEntity.ok(response);
}