首页 > 解决方案 > CORS policy when deleting an item

问题描述

error message in google chromeWhen I try to delete an item I am getting an error.

When I added spring security to my backend i faced problem with csrf and could not event display my data from database in Angular. So, I made some steps: I have added @WebSecurityConfigurerAdapter into my backend. Later set Interceptor in Angular and after this I was able to load my data using spring security in background.

@EnableWebSecurity
@Configuration
public class SpringSecurity extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .authorizeRequests()
                .antMatchers(HttpMethod.OPTIONS,"/**").permitAll()
                .anyRequest().authenticated()
                .and()
                //.formLogin().and()
                .httpBasic();
    }
}

Angular part my service with Interceptor

import { Injectable } from '@angular/core';
import {HttpHandler, HttpInterceptor, HttpRequest} from '@angular/common/http';


@Injectable({
  providedIn: 'root'
})
export class HttpInterceptorService implements HttpInterceptor {

  intercept(request: HttpRequest<any>, next: HttpHandler) {
    const username = 'damian';
    const password = 'damian';
    const basicAutHeaderString = 'Basic ' + window.btoa(username + ':' + password);



    request = request.clone(
      {
        setHeaders: {
          Authorization: basicAutHeaderString
        }
      }
    );
    return next.handle(request);
  }


  constructor() { }


}

Getting single item from backend:

  deleteSingleTodo(id) {
    return this.http.delete<Todo>(`http://localhost:8081/${id}`);
  }

My delete method which is triggered by (click) button:

  deleteTodo(id) {
    console.log(`delete todo ${id}` )
    this.getDataService.deleteSingleTodo( id).subscribe (
      response => {
        console.log(response);
        this.message = `Delete of Todo ${id} Successful!`;
        this.refreshTodos();
      }
    );
  }

I also provided HTTP_INTERCEPTORS in app.module.ts
 providers: [
    { provide: HTTP_INTERCEPTORS, `useClass: HttpInterceptorService, multi:` true}

],[my error message in google][1]

标签: angularspring-bootcors

解决方案


您可以简单地添加一个过滤器来应用 CORS,如下所示,看看它是否有效

@Component
public class CrossOriginFilter implements Filter {
    private static final Logger log = LoggerFactory.getLogger(CrossOriginFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

        // Called by the web container to indicate to a filter that it is being
        // placed into service.
        // We do not want to do anything here.
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
        log.info("Applying CORS filter");
        HttpServletResponse response = (HttpServletResponse) resp;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PATCH, PUT, DELETE, OPTIONS");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Origin, Authorization, X-Requested-With, Content-Type, Accept, X-Auth-Token, X-CSRF-TOKEN");
        chain.doFilter(req, resp);
    }

    @Override
    public void destroy() {

        // Called by the web container to indicate to a filter that it is being
        // taken out of service.
        // We do not want to do anything here.
    }
}

推荐阅读