【问题标题】:how to avoid CORS policy error in angular PUT method [duplicate]如何避免角度 PUT 方法中的 CORS 策略错误 [重复]
【发布时间】:2020-01-28 06:45:56
【问题描述】:

我正在尝试在 Angular 中执行 PUT 方法,

app.component.ts:

this.http.put( this.updateurl+ this.userid, JSON.stringify(user.value))
.subscribe(response =>{
  console.log(response);
});

当我这样做时,我收到如下错误:

   Access to XMLHttpRequest at 'http:// ***********' from origin 'http://localhost:4200' has been 
   blocked by CORS policy: Method PUT is not allowed by Access-Control-Allow-Methods in preflight 
   response.

我该如何解决这个问题。

【问题讨论】:

  • 您的服务器端技术是什么? cors 策略可以在服务器端添加,而不是在角度端。
  • 您应该在服务器端启用 cors(跨源资源共享)。您可以为特定 url 和所有 url 启用它。
  • 请阅读this

标签: javascript angular core


【解决方案1】:

如果您要访问公共 API,则需要在您的应用程序中配置一个角度代理。参考这个:https://github.com/angular/angular-cli/blob/master/docs/documentation/stories/proxy.md

【讨论】:

  • CORE 问题,建议设置代理绕过?
  • 如果您要访问公共 API,这将是解决方案。如果没有,您可以在后端允许它
【解决方案2】:
No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

这是因为 Same Origin Policy – 它规定每个 AJAX 请求都必须与 hostprotocol 完全匹配>端口您的网站。

如何解决:

只需使用 * 提供对所有主机协议端口的访问。

修改服务器以添加标头 Access-Control-Allow-Origin: * 以启用来自任何地方的跨域请求(或指定域而不是 *)。 这应该可以解决您的问题。

在您的项目 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.methods</param-name>
        <param-value>GET, POST, PUT, DELETE, OPTIONS, HEAD</param-value>
    </init-param>  
</filter>

现在要限制对特定主机协议端口的访问,您可以使用以下参数值

<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> -->
        <param-value>http://localhost:4000,https://myapp.com</param-value>
    </init-param>
    <init-param>
        <param-name>cors.allowed.methods</param-name>
        <param-value>GET, POST, PUT, DELETE, OPTIONS, HEAD</param-value>
    </init-param>  
</filter>

现在这种情况下,只允许来自以下 url 的请求,而其他的会抛出 CORS 错误,即使它们在主机、协议或端口上有轻微的变化

http://localhost:4000https://myapp.com

以上仅供参考

  • http , https --> 协议

  • localhost , myapp -> 主机

  • 4000 --> 端口

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    • 2011-04-09
    • 2021-09-05
    • 2021-04-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多