CORS 预检的响应是 405(方法不允许)错误

Response for CORS preflight is 405 (Method Not Allowed) error

我正在尝试从我的 angular 网络应用程序上传 foursquare 用户的个人资料照片。我正在使用 "users/update" 终点 - https://developer.foursquare.com/docs/users/update

这是我的模板,

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

这是我的组件代码,

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)                                     
    );
}

我在控制台收到 405(方法不允许)预检响应有无效的 HTTP 状态代码 405 错误。

您可能想从前端 JavaScript 代码中删除以下内容开始:

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

Access-Control-Allow-Origin是服务器发送的响应header;将其添加为请求 header 的唯一效果是触发一个 CORS preflight OPTIONS request,但会失败。

您现在看到的情况是,因为您的代码添加了 Access-Control-Allow-Origin 作为请求 header,您的浏览器正在发送 CORS preflight OPTIONS request;为了使浏览器认为预检成功,https://api.foursquare.com/v2/users/self/update 端点必须使用 200 OK 或 204 状态代码响应 OPTIONS 请求。

但是您收到的 405“(Method Not Allowed)”响应表明 Foursquare API 端点未配置为处理 OPTIONS 请求。因此预检失败,您的浏览器永远不会继续执行 POST 请求它尝试发送的代码。

但是,来自 Foursquare API 端点的非 OPTIONS 请求的响应确实包括 Access-Control-Allow-Origin 响应 header。因此,只要您不从客户端添加 Access-Control-Allow-Origin,并且只要请求没有其他特征会触发浏览器进行预检,问题中的代码就应该按预期工作。

如果部署后在 IIS 上出现此问题,我建议您将其添加到 Web.config 内部标记中:

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