【问题标题】:Response for CORS preflight is 405 (Method Not Allowed) errorCORS 预检的响应是 405(不允许的方法)错误
【发布时间】:2018-01-26 17:03:40
【问题描述】:

我正在尝试从我的 Angular Web 应用程序上传foursquare 用户的个人资料照片。我正在使用“用户/更新”端点 - 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 (Method Not Allowed)Response for preflight has invalid HTTP status code 405 在控制台中出现错误。

【问题讨论】:

    标签: angular cors foursquare angular-http http-status-code-405


    【解决方案1】:

    您可能希望首先从前端 JavaScript 代码中删除以下内容:

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

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

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

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

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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 2014-01-09
        • 2017-11-13
        • 2016-12-02
        • 2015-11-25
        • 2018-06-16
        • 1970-01-01
        • 2016-08-05
        • 2013-03-13
        • 1970-01-01
        相关资源
        最近更新 更多