【问题标题】:CORS Method PATCH is not show in Access-Control-Allow-MethodsCORS 方法补丁未显示在 Access-Control-Allow-Methods 中
【发布时间】:2020-12-19 00:10:48
【问题描述】:

我正在开发一个 Angular 9 应用程序并使用 Angular httpclient 发送补丁要求。但是由于预检请求未通过,要求总是失败。我知道我可以添加一些关于允许方法的设置,并且我做到了,但仍然无法正常工作,似乎我的设置不适用于 angular httpclient。我在这个问题上卡了很久,请给一些关于这个问题的建议。 服务器是 Tomcat 7(7.0.106),rest api 是 jersery,这里是 web.xml 中设置的一部分

    <filter>
        <filter-name>CorsFilter</filter-name>
        <filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
        <init-param>
            <param-name>cors.allowed.origins</param-name>
            <param-value>*</param-value>
        </init-param>
        <init-param>
            <param-name>cors.allowed.headers</param-name>
            <param-value>Authorization,Content-Type,X-Requested-With,Origin,Accept,Access-Control-Request-Method,Access-Control-Request-Headers</param-value>
        </init-param>
        <init-param>
            <param-name>cors.allowed.methods</param-name>
            <param-value>GET, POST, PUT, DELETE, OPTIONS, HEAD, PATCH</param-value>
        </init-param>
    </filter>

这是 Angular httpclient 的 Chrome 中的请求详细信息(失败的那个)

**General**
Request URL: http://localhost:8080/api/v1/user/testPatch
Request Method: OPTIONS
Status Code: 200 OK
Remote Address: [::1]:8080
Referrer Policy: strict-origin-when-cross-origin
**Request Header**
...
Accept: */*
Accept-Encoding: gzip, deflate, br
Access-Control-Request-Headers: content-type
Access-Control-Request-Method: PATCH
Cache-Control: no-cache
Connection: keep-alive
Host: localhost:8080
Origin: http://localhost:4200
Pragma: no-cache
Referer: http://localhost:4200/
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-site
...
**Response Header**
Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: Authorization,Content-Type,X-Requested-With,Origin,Accept,Access-Control-Request-Method,Access-Control-Request-Headers
Access-Control-Allow-Headers: content-type
Access-Control-Allow-Methods: GET, PUT, POST, DELETE, HEAD, OPTIONS
Access-Control-Allow-Origin: http://localhost:4200
Allow: OPTIONS,PATCH
Content-Length: 803
Content-Type: application/vnd.sun.wadl+xml
Server: HTTP Server
...

如您所见,PATCH 方法不在“Access-Control-Allow-Methods”中,但我已经在 web.xml 中设置了它,我不知道我缺少什么。顺便说一句,我可以通过 Postman 成功调用相同的 api,并且响应的“Access-Control-Allow-Methods”设置与我在 web.xml 中设置的完全一样

【问题讨论】:

  • 您的服务器是否以不同的 haeder 响应,具体取决于您使用的客户端?你有任何带有 cors 配置的课程吗?
  • 为什么会有两个Access-Control-Allow-Headers响应头?

标签: java angular cors jersey tomcat7


【解决方案1】:

我终于找到了问题,但首先感谢@Andrei 和@Paul Samsotha 的回复。这个问题的原因是我使用了 Chrome cors 插件,该插件将覆盖 cors 请求的 allow 方法,并且 alllow 方法的默认值不包括“PATCH”。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-09
    • 2020-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-02
    • 1970-01-01
    • 2019-04-28
    相关资源
    最近更新 更多