-1

I am trying todo PUT method in Angular,

app.component.ts:

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

when I do this I am getting error like :

   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.

how can I solve this.

Vega
  • 27,856
  • 27
  • 95
  • 103
Ram Kumar
  • 245
  • 1
  • 2
  • 10

2 Answers2

0

If you are going to access a public API, you need to configure an angular proxy into your application. Refer this: https://github.com/angular/angular-cli/blob/master/docs/documentation/stories/proxy.md

Kushan Sameera
  • 169
  • 1
  • 1
  • 9
0
No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

This is because of the Same Origin Policy – it says that every AJAX request must match the exact host, protocol, and port of your site.

How to fix it:

Simply just provide access to all the host, protocol, and port by using *.

Modify the server to add the header Access-Control-Allow-Origin: * to enable cross-origin requests from anywhere (or specify a domain instead of *). This should solve your problem.

In you projects web.xml add the following 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>
    </init-param>
    <init-param>
        <param-name>cors.allowed.methods</param-name>
        <param-value>GET, POST, PUT, DELETE, OPTIONS, HEAD</param-value>
    </init-param>  
</filter>

Now for limiting the access to only specific host, protocol, or port you can use the following param-value

<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>

Now here is this case only the requests from the following urls will be allowed while other will throw a CORS error even if they have a slight change in host, protocol, or port

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

FYI in above

  • http , https --> protocols

  • localhost , myapp -> hosts

  • 4000 --> port

fatimasajjad
  • 605
  • 8
  • 16