【问题标题】:angular : Did not find method in CORS header ‘Access-Control-Allow-Methods角度:在 CORS 标头“Access-Control-Allow-Methods”中找不到方法
【发布时间】:2020-04-22 09:02:24
【问题描述】:

我在后端使用弹簧靴,在前端使用 angular .. 我正在尝试 删除 一个项目,但我不工作..当我尝试 get 它可以工作,但是 Delete 它不起作用..

  • 服务 ts
import { Injectable } from '@angular/core';
import { HttpClient,HttpHeaders } from '@angular/common/http';
import { AuthService } from 'app/services/auth.service';


@Injectable({
  providedIn: 'root'
})
export class CollaboratorsService {
url="http://localhost:8080/"

jwt=this.auth.getjwt();

constructor(private http:HttpClient,private auth:AuthService) {  }


  public getCollaborators(name){
    let link="collaboratorses?search="+name;
    return this.auth.getRessource(link);

  }

  public deleteCollaborator(id){
    let fullUrl=this.url+"entreprise/collaborator/"+id;
    console.log("full "+fullUrl);
    let headers = new HttpHeaders({
    'Authorization': this.jwt,
    "Access-Control-Allow-Methods":"GET, POST, DELETE, PUT",
    'Content-Type': 'application/json',
    'Access-Control-Allow-Origin': '*'
     }); 
    return this.http.delete(fullUrl,{headers:headers});
  }
}
  • 组件 ts
onDeleteColl(id){
    let c=confirm("are You Sure you want Delete This Collaborator!");
    if(!c){
        return;
    }else{
        this.collService.deleteCollaborator(id).subscribe(res =>{
      console.log(res);
    },err =>{
        console.log(err);
    });
        this.onGetcoll();
    }
}

当我在 Firefox 上使用 RESTCLIENT 扩展时,当我尝试发布、获取或删除时,一切正常,但是当我尝试使用 angular 的 Delete 时,我遇到了这个问题

ps:我已经在后端添加了允许交叉,所以我认为问题仅在于角度

protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {

        response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Access-Control-Allow-Headers","Origin, Accept, X-Requested-With, Content-Type, Access-Control-Request-Methods, Access-Control-Request-Headers, Authorization");                                                          
        response.addHeader("Access-Control-Expose-Headers", "Access-Control-Allow-Origin, Access-Control-Allow-Credentials, Authorization ");
        response.addHeader("Access-Control-Allow-Methods","Get, Post, Put, Delete, Patch, Options");

【问题讨论】:

  • 首先从你的 Angular 服务中删除访问控制标头..

标签: angular spring spring-boot


【解决方案1】:

从 Angular 中删除这些标头,因为它们是服务器端标头

"Access-Control-Allow-Methods":"GET, POST, DELETE, PUT",
'Access-Control-Allow-Origin': '*'

您还可以删除 Content-Type 标头,因为它是由 angular 自动设置的

和服务器端,尝试用大写值设置允许的方法

response.addHeader("Access-Control-Allow-Methods","GET, POST, PUT, DELETE, PATCH, OPTIONS");

【讨论】:

  • 谢谢它现在起作用了。我不知道标题是敏感的大小写。非常感谢
猜你喜欢
  • 2017-05-02
  • 2017-06-09
  • 1970-01-01
  • 1970-01-01
  • 2019-06-19
  • 2016-08-06
  • 1970-01-01
  • 2016-10-30
  • 1970-01-01
相关资源
最近更新 更多