预检的响应具有无效的HTTP状态代码405 AngularJS

时间:2016-06-09 14:23:04

标签: javascript angularjs cors http-get postman

我收到了这个错误:

XMLHttpRequest无法加载http://apidev.facu.la/api/json/infotag/search/?criteria=&infotagType=book&companyid=2。尝试执行此httpget调用时,预检的响应具有无效的HTTP状态代码405:

  $http({
                method: 'GET',
                dataType: "json",
                url: 'http://apidev.facu.la/api/json/infotag/search/?criteria=&infotagType=book&companyid=2',
                headers: {
                    "Content-Type": "application/json"
                }
            }).then(function successCallback(response) {
                alert('ok');
            }, function errorCallback(response) {
                alert('error');
                console.log(response);
            });

知道我错过了什么吗?邮差工作很好。

更新

端点代码:

  [WebInvoke(Method = "GET",
            RequestFormat = WebMessageFormat.Json,
            ResponseFormat = WebMessageFormat.Json,
            BodyStyle = WebMessageBodyStyle.Bare,
            UriTemplate = "/json/infotag/search/?criteria={criteria}&infotagType={infotagType}&companyid={companyid}")]
        public XElement InfoTagSearchXML_json(string criteria, string infotagType, int companyid)
        {
            return InfoTagSearchXML(criteria, infotagType, companyid);
        }

2 个答案:

答案 0 :(得分:0)

您可以将Method OPTIONS的WebInvoke添加到ServiceContract,如下所示:

[ServiceContract]
public interface ITestService
{
    [WebInvoke(Method = "OPTIONS", UriTemplate = "*")]
    void getOptions();

    ... other invokes
}

public class Service : ITestService
{
    public void getOptions()
    {
        WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Origin", "*");
        WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Methods", "GET, OPTIONS");
        WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Headers", "Content-Type");
    }

    ... other invokes
}

答案 1 :(得分:0)

执行以下操作:

 Install-Package Microsoft.AspNet.WebApi.Cors

然后转到Web.config并删除这些行(如果有的话)

<remove name="X-Powered-By" />
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Accept, Content-Type, Origin" />
<add name="Access-Control-Allow-Methods" value="GET, PUT, POST, DELETE, OPTIONS" />

并在App_Start文件夹的WebApiConfig.cs文件中添加以下代码:

var enableCorsAttribute = new EnableCorsAttribute("*",
                          "Origin, Content-Type, Accept",
                          "GET, PUT, POST, DELETE, OPTIONS");
config.EnableCors(enableCorsAttribute);