angular - 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]
解决方案
您可以简单地添加一个过滤器来应用 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.
}
}
推荐阅读
- html - 你能用 CSS 做数据绑定吗?
- angular - 如何在 Angular 组件中使用 Bootstrap SCSS 函数?
- arduino - 部署在 Arduino 示例草图 hello_world 上的 TensorFlow-lite
- flutter - Android 依赖在编译和运行时有不同的版本:runing FCM dependency
- javascript - 用javascript读取ble包的制造数据
- c# - 如何通过 C# ASP.NET 使用 FTPWebRequest 下载“.xlsx”文件
- typescript - React-Redux Reducer 没有被调用
- html - 如何为菜单中的图标添加超链接?
- javascript - 如何使用 React 在 JS 文件中使用 Elm?
- ruby - Ruby嵌套使用变量有错误未定义方法`[]'