我试图调用API。我用POSTMAN测试了调用,它工作正常,但是当我尝试使用Angular 2 HTTP时出现错误。
以下是错误:OPTIONS [URL] 405(不允许使用方法)。我在localhost上使用我的测试服务器连接到另一台服务器上的API。该服务确实具有Access-Control-Allow-Origin。
这是我的代码。
getAllAlerts(){
let headers = new Headers({'authorization':'Bearer ACCESSTOKEN'}),
options = new RequestOptions({headers: headers});
return this.http.get(this.mentionUrl,options).map((resp) => resp.json());
}
当我查看Chrome上的网络(标签)时,请求方法更改为OPTIONS,状态代码为405 Method Not Allowed。
答案 0 :(得分:0)
在您的API上,您还必须指定允许的方法和标题。
因此,例如,当使用Rails和Rack :: CORS gem时,配置如下:
# configure rails to allow CORS from all sources
config.middleware.insert_before 0, "Rack::Cors" do
allow do
origins '*'
resource '*', :headers => :any, :methods => [:get, :post, :options]
end
end
以上配置Rails以允许方法的CORS请求:GET,POST和OPTIONS。
由于CORS的工作原理,OPTIONS是必要的 - 每当您进行跨源请求时,浏览器首先尝试OPTIONS请求并检查Access-Control-Allow-Origin标头的响应头。只有当浏览器在响应中看到该标题时才会发送实际请求