相关疑难解决方法(0)

CORS - Ajax错误函数将返回401的API请求的错误代码报告为0

背景

当身份验证(JWT)成功时,我在本地开发环境中使用CORS.我的客户端页面运行localhost并调用api.mycompany.com获取数据.我的api项目检查有效的JWT,如果通过,则返回内容.我花了一段时间才到这里,但这一切都很好.

如果我没有发送有效的JWT,则api会正确响应401(在Fiddler中检查),但客户端上的错误函数回调报告错误代码为0且状态为"错误".

我希望ajax回调函数检查错误的状态代码,如果是401,请检查标题名为location的标题(将包含uri到身份验证服务).

建立

  • (API项目)在本地IIS Express上运行MVC4项目的Visual Studio 2012实例

    • 本地主机文件将127.0.0.1映射到api.mycompany.com
    • 将项目 - >属性 - > Web设置为IIS Express
      • 使用本地IIS Express(已选中)
      • 项目网址: http://localhost:8080
      • 创建虚拟目录
      • 覆盖应用程序根URL(已选中)
      • 覆盖应用程序根URL: http://api.mycompany.com:8080
    • 在站点下的applicationhost.config中:

      <site name="StuffManagerAPI" id="1">
        <application path="/" applicationPool="Clr4IntegratedAppPool">
          <virtualDirectory path="/" physicalPath="C:\Users\me\Documents\Visual Studio 2012\Projects\StuffManagerAPI\StuffManagerAPI" />
        </application>
        <bindings>
          <binding protocol="http" bindingInformation="*:8080:localhost" />
          <binding protocol="http" bindingInformation="*:8080:api.mycompany.com" />
        </bindings>
      </site>
      
      Run Code Online (Sandbox Code Playgroud)
  • (客户端项目)将Visual Studio实例与ASP.net空Web应用程序分开

    • 将项目 - >属性 - > Web设置为IIS Express
      • 使用本地IIS Express(已选中)
      • 项目网址: http://localhost:22628
      • 创建虚拟目录
  • 使用Google Chrome作为测试客户端

  • 使用Fiddler查看流量

我认为这些应该是我的概念验证中的重要部分.再次,CORS预检和数据检索都可以正常工作.这只是未经授权的案例无效.如果您还有其他需要,请告诉我.谢谢您的帮助.

API项目

授权标题处理程序

using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using …
Run Code Online (Sandbox Code Playgroud)

ajax jquery cors

9
推荐指数
1
解决办法
4606
查看次数

标签 统计

ajax ×1

cors ×1

jquery ×1