Response for CORS preflight is 405 (Method Not All

2019-02-26 05:36发布

问题:

I am trying to upload foursquare user's profile photo from my angular web application. I am using "users/update" end point - https://developer.foursquare.com/docs/users/update

Here is my template,

<input type="file" (change)="fileChange($event)" placeholder="Upload file">

Here is my component code,

fileChange(event) {

    let fd:FormData=new FormData();
    fd.append("photo",event.target.files[0]);

    let headers=new Headers();
    headers.append("Content-Type","multipart/form-data");
    headers.append("Accept","application/json");
    headers.append("Access-Control-Allow-Origin","true");


    let options=new RequestOptions({headers:headers});


    this.http.post("https://api.foursquare.com/v2/users/self/update?oauth_token=myauthtoken&v=20160108",fd,options)
    .map(response=>response.json())
    .subscribe(                                      
             data=>console.log(data),
             error=>console.log(error)                                     
    );
}

I am getting 405 (Method Not Allowed) and Response for preflight has invalid HTTP status code 405 errors in the console.

回答1:

You probably want to start by removing the following from your frontend JavaScript code:

headers.append("Access-Control-Allow-Origin","true")

Access-Control-Allow-Origin is a response header for servers to send; the only effect adding it as a request header will ever have is to trigger a CORS preflight OPTIONS request that’ll fail.

What you see happening now is that because your code adds Access-Control-Allow-Origin as a request header, your browser is sending a CORS preflight OPTIONS request; and for the browser to consider that preflight successful, the https://api.foursquare.com/v2/users/self/update endpoint must respond to the OPTIONS request with a 200 OK or 204 status code.

But that 405 “(Method Not Allowed)” response you’re getting instead indicates that Foursquare API endpoint isn’t configured to handle OPTIONS requests. So the preflight fails and your browser never moves on to doing the POST request your code it trying to send.

However, responses to non-OPTIONS requests from that Foursquare API endpoint do include the Access-Control-Allow-Origin response header. So the code in the question should work as expected as long as you’re not adding Access-Control-Allow-Origin from the client side, and as long as there’s no other characteristic of the request that will trigger browsers to do a preflight.



回答2:

If this issues occurs on IIS after deployment, i will suggest you add this on your Web.config inside tag:

<modules>
    <remove name="WebDAVModule" />
</modules>