XmlHttpRequest无法加载API_URL。预检的响应具有无效的HTTP状态代码401

时间:2017-08-31 09:04:30

标签: angularjs asp.net-web-api xmlhttprequest

我正在使用HTTPRestService方法通过api调用获取一些数据。这是我的代码:

function getDataFromAPI(inputData) {
    var deferred = $q.defer();
    $http.post(API_URL_HERE, inputData).success(function (data) {
        deferred.resolve(data);

    }).error(function (data) {
        deferred.reject();
    });

    return deferred.promise;
}   

这是我在API项目中的web.config文件中编写的代码:

<system.webServer>
<security>
  <requestFiltering>
    <requestLimits maxAllowedContentLength="2147483648" />
  </requestFiltering>
</security>
<httpProtocol>
  <customHeaders>
    <clear />
    <add name="Access-Control-Allow-Origin" value="*" />
    <add name="Access-Control-Allow-Headers" value="Origin, X-Requested-
    With,Content-Type,Accept" />
    <add name="Access-Control-Allow-Methods" 
    value="GET,POST,PUT,DELETE,OPTIONS" />
    <add name="Access-Control-Allow-Credentials" value="true"/>
  </customHeaders>
  </httpProtocol>
 <handlers>
  <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
  <remove name="OPTIONSVerbHandler" />
  <remove name="TRACEVerbHandler" />
  <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" 
  type="System.Web.Handlers.TransferRequestHandler" 
  preCondition="integratedMode,runtimeVersionv4.0" />
  </handlers></system.webServer>

这是我在Global.asax.cs文件中编写的代码:

internal protected void Application_BeginRequest(object sender, EventArgs e)
    {
        //// Get objects.
        //HttpContext context = base.Context;
        //HttpResponse response = context.Response;
        //// Complete.
        //base.CompleteRequest();

        if (Context.Request.HttpMethod == "OPTIONS")
        {
            Context.Response.AddHeader("Access-Control-Allow-Origin", Context.Request.Headers["Origin"]);
            Context.Response.AddHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
            Context.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
            Context.Response.AddHeader("Access-Control-Allow-Credentials", "true");
        }
    }

我仍然在Chrome和边缘浏览器中收到这401个未经授权的错误。 我需要做些什么才能解决这个问题?

0 个答案:

没有答案